[英]Re-render child after parent state change with get request
So I'm a beginner with react and I was wondering how to re-render the child after setting the state in the parent (from the child).所以我是一个有反应的初学者,我想知道如何在父级(来自子级)中设置 state 后重新渲染子级。 Here's a code sample.
这是一个代码示例。 I have a function that calls a GET request using Axios and when I press the button in the child component ideally it will update the state in the parent and also re-render the child but it only does the former.
我有一个 function 使用 Axios 调用 GET 请求,当我按下子组件中的按钮时,理想情况下它会更新 state 只在前一个子组件中,但它也重新生成。
Parent:家长:
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}/>)
}
// ...
Child:孩子:
class Child extends Component {
// ...
render() {
const { data, fetchData } = this.props
// render data
return <button onClick={fetchData}>Change data then fetch</button>
}
}
Also, are you supposed to make a local state in the Child and set it as a copy of the Parent's state or just passing it down as a prop is okay?另外,您是否应该在子级中创建本地 state 并将其设置为父级 state 的副本,或者只是将其作为道具传递可以吗?
Your parent component holds the data and the child uses it.您的父组件保存数据,子组件使用它。 It seems to me you're doing it the right way.
在我看来,您的做法是正确的。 Here is a fully working example: Codesandbox
这是一个完整的示例: 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} />;
}
}
Note I renamed your child prop fetchData
into onAction
(I don't know what's the name of the action that triggers a refresh, could be onRefresh
).请注意,我将您的子道具
fetchData
重命名为onAction
(我不知道触发刷新的操作的名称是什么,可能是onRefresh
)。 It's always best to see components props with separation between data attributes and event attributes .始终最好看到将数据属性和事件属性分开的组件道具。
Even standard components have it this way: <input value={user.firstname} onChange={doSomething} />
.即使是标准组件也有这种方式:
<input value={user.firstname} onChange={doSomething} />
。 So, better to prefix events by on
, then the parent decides what to do with it.因此,最好在事件前加上
on
,然后由父母决定如何处理它。 It's not the child's concern.这不是孩子的问题。
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.