我有一个 React 组件,当我在子组件上调用 onSubmit 时需要更新该组件
需要更新的父组件如下所示:
componentDidMount() {
axios.get('/todo')
.then(function (response) {
this.setState({
todoList: response.data
})
}.bind(this))
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<div>
<Form/>
{this.state.todoList.map(todo => {
return (
<TodoItem
id={todo._id}
key={todo._id}
itemToDo={todo.todoItem}
/>
);
})}
</div>
)
}
当我提交<Form/>
时我调用的组件
handleSubmit(e) {
e.preventDefault();
axios.post('/todo', {
todoItem: this.state.todoItem
})
}
我需要更新父组件,以便从服务器获取更新的列表
最佳答案
我不完全确定你的问题,但你可以将函数(updateParent)作为属性从父组件传递到子组件,当你想更新父组件时,在子组件中调用 this.props.propFromParentComponent 。如果您希望父组件更新,请使用 this.setState({..}) 并更新组件的状态,以更新此函数内的父组件(updateParent)。
关于javascript - React 更新父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45196682/