[英]Re-render child after parent state change with get request
所以我是一個有反應的初學者,我想知道如何在父級(來自子級)中設置 state 后重新渲染子級。 這是一個代碼示例。 我有一個 function 使用 Axios 調用 GET 請求,當我按下子組件中的按鈕時,理想情況下它會更新 state 只在前一個子組件中,但它也重新生成。
家長:
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
data: []
}
}
fetchData = () => {
axios
.get(url)
.then(res => this.setState({data: res.data}))
}
Render() {
return (<Child data={this.state.data} fetchData={this.fecthData}/>)
}
// ...
孩子:
class Child extends Component {
// ...
render() {
const { data, fetchData } = this.props
// render data
return <button onClick={fetchData}>Change data then fetch</button>
}
}
另外,您是否應該在子級中創建本地 state 並將其設置為父級 state 的副本,或者只是將其作為道具傳遞可以嗎?
您的父組件保存數據,子組件使用它。 在我看來,您的做法是正確的。 這是一個完整的示例: Codesandbox
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
this.updateData = this.updateData.bind(this);
}
async fetchData() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
return response.json();
}
updateData() {
this.setState({ data: [] }) // Creates a flicker, just so you see it does refresh the child
this.fetchData().then((res) => this.setState({ data: res }));
}
render() {
return <Child data={this.state.data} onAction={this.updateData} />;
}
}
請注意,我將您的子道具fetchData
重命名為onAction
(我不知道觸發刷新的操作的名稱是什么,可能是onRefresh
)。 始終最好看到將數據屬性和事件屬性分開的組件道具。
即使是標准組件也有這種方式: <input value={user.firstname} onChange={doSomething} />
。 因此,最好在事件前加上on
,然后由父母決定如何處理它。 這不是孩子的問題。
class Child extends Component {
render() {
const { data, onAction } = this.props;
return (
<>
<button onClick={onAction}>Change data then fetch</button>
{data.map((item) => (
<div key={item.id}>
{item.id} - {item.title}
</div>
))}
</>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.