如何在 React 中从另一个组件设置一个组件的状态 [英] How to set one component's state from another component in React
问题描述
假设我有以下名为 Home 的组件:
this.state = {帖子:[]}componentDidMount() {...从api获取数据} (<发布键={post.id} post={post}/>))}
PostForm 组件与新的 Post 一起提交后,我将如何更新 Home 的状态,或从 api 重新获取数据.
欢迎来到 SO!
从孩子设置父状态:
如果你想让你的子组件访问你父组件的状态,只需将 setState()
作为你父类中的 prop 传递,就像这样......
this.setState(state)}/>
然后,稍后在 PostForm.js
中,只需像这样设置父状态....
this.props.setParentState(newParentStateObject);
从父级设置子状态:
假设你现在想做相反的事情:从父组件更新子组件的状态?这也很简单,在定义
...
{this.postform = 实例}}/>
然后你可以直接在你的父类中设置postform的状态...
this.postform.setState(newChildStateObject);
状态可能会发生很多事情,所以如果您不确定,请尝试创建一个 testFunc() {console.log('test');}
,然后尝试传递/激活这在父母和孩子之间.
Say I have the following component named Home:
this.state = {
posts: []
}
componentDidMount() {
... data is fetched from api
}
<div
<PostForm />
{this.state.posts.map(post => (
<Post key={post.id} post={post} />
))}
</div>
How would I update the state of Home, or re fetch data from the api after the the PostForm component is submitted with a new Post.
Welcome to SO!
Setting the parent state from the child:
If you want your child component to have access to your parent component's state, just pass setState()
as a prop in your parent class, like so...
<PostForm
setParentState={(state) => this.setState(state)}
/>
Then, later in PostForm.js
, just set the parent state like so....
this.props.setParentState(newParentStateObject);
Setting the child state from the parent:
Suppose you want to do the opposite now: update the state of the child component from the parent? That's just as easy, set a reference when defining <PostForm/>
...
<PostForm
ref={(instance) => {this.postform = instance}}
/>
Then you can set the postform's state directly in your parent class...
this.postform.setState(newChildStateObject);
A lot can happen with the state, so if you're not sure, try making a testFunc() {console.log('test');}
, and then try passing/activating this between parent and child.
这篇关于如何在 React 中从另一个组件设置一个组件的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!