如何在React中更新父状态? [英] How to update parent's state in React?

查看:145
本文介绍了如何在React中更新父状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的结构如下所示:

Component 1  

 - |- Component 2


 - - |- Component 4


 - - -  |- Component 5  

Component 3

组件3应显示一些数据,具体取决于组件5的状态。
由于道具是不可变的,我不能只需在组件1中保存它的状态并转发它,对吧?是的,我读过有关redux的内容,但不想使用它。我希望只有反应就可以解决它。我错了吗?

Component 3 should display some data depending on state of Component 5. Since props are immutable, I can't simply save it's state in Component 1 and forward it, right? And yes, I've read about redux, but don't want to use it. I hope that it's possible to solve it just with react. Am I wrong?

推荐答案

对于子父沟通,您应该传递一个函数,将状态从父设置为子设置,如下所示

For child-parent communication you should pass a function setting the state from parent to child, like this

class Parent extends React.Component {
  constructor(props) {
    super(props)

    this.handler = this.handler.bind(this)
  }

  handler() {
    this.setState({
      someVar: someValue
    })
  }

  render() {
    return <Child handler = {this.handler} />
  }
}

class Child extends React.Component {
  render() {
    return <Button onClick = {this.props.handler}/ >
  }
}

这样孩子可以用以下方式更新父母的状态使用道具传递函数的调用。

This way the child can update the parent's state with the call of a function passed with props.

但是你必须重新考虑组件的结构,因为据我所知,组件5和3不相关。

But you will have to rethink your components' structure, because as I understand components 5 and 3 are not related.

一种可能的解决方案是将它们包含在更高级别的组件中,该组件将包含组件1和3的状态。该组件将通过props设置较低级别的状态。

One possible solution is to wrap them in a higher level component which will contain the state of both component 1 and 3. This component will set the lower level state through props.

这篇关于如何在React中更新父状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆