如何在React中更新父状态

JavaScript

AEva伽罗

2020-03-10

我的结构如下所示:

Component 1  

 - |- Component 2


 - - |- Component 4


 - - -  |- Component 5  

Component 3

组件3应该根据组件5的状态显示一些数据。由于道具是不可变的,我不能简单地将其状态保存在组件1中并转发它,对吗?是的,我已经阅读了有关redux的内容,但不想使用它。我希望有可能通过反应来解决。我错了吗?

第403篇《如何在React中更新父状态》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
神无LEYTony 2020.03.10
<Footer 
  action={()=>this.setState({showChart: true})}
/>

<footer className="row">
    <button type="button" onClick={this.props.action}>Edit</button>
  {console.log(this.props)}
</footer>

Try this example to write inline setState, it avoids creating another function.
飞云小哥 2020.03.10

如果这种情况并没有遍及每个地方,那么您可以使用React的上下文,特别是如果您不想引入状态管理库引入的所有开销时。另外,它更容易学习。但是要小心,您可能会过度使用它并开始编写错误的代码。基本上,您定义了一个Container组件(将为您保留并保持该状态),使所有对写入/读取该数据段感兴趣的组件成为其子级(不一定是直接子级)。

https://reactjs.org/docs/context.html

您也可以适当地使用普通React。

<Component5 onSomethingHappenedIn5={this.props.doSomethingAbout5} />

将doSomethingAbout5传递给组件1

    <Component1>
        <Component2 onSomethingHappenedIn5={somethingAbout5 => this.setState({somethingAbout5})}/>
        <Component5 propThatDependsOn5={this.state.somethingAbout5}/>
    <Component1/>

如果这是一个常见问题,则应开始考虑将应用程序的整个状态转移到其他地方。您有几种选择,最常见的是:

https://redux.js.org/

https://facebook.github.io/flux/

基本上,不是在组件中管理应用程序状态,而是在发生某些事情来更新状态时发送命令。组件也从此容器中获取状态,因此所有数据都被集中。这并不意味着不能再使用本地状态,而是一个更高级的主题。

null 2020.03.10

我已经多次使用此页面上评分最高的答案,但是在学习React的同时,我发现了一种更好的方法,无需绑定,也没有在props中使用内联函数。

看看这里:

class Parent extends React.Component {

  constructor() {
    super();
    this.state={
      someVar: value
    }
  }

  handleChange=(someValue)=>{
    this.setState({someVar: someValue})
  }

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

}

export const Child = ({handler}) => {
  return <Button onClick={handler} />
}

该键位于箭头功能中:

handleChange=(someValue)=>{
  this.setState({someVar: someValue})
}

您可以在这里阅读更多内容希望这对某人有用=)

番长猴子古一 2020.03.10

我发现以下工作解决方案将带有子参数的onClick函数参数从子级传递到父级组件:

家长班:

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

    // Bind the this context to the handler function
    this.handler = this.handler.bind(this);

    // Set some state
    this.state = {
        messageShown: false
    };
}

// This method will be sent to the child component
handler(param1) {
console.log(param1);
    this.setState({
        messageShown: true
    });
}

// Render the child component and set the action property with the handler as value
render() {
    return <Child action={this.handler} />
}}

子班:

class Child extends React.Component {
render() {
    return (
        <div>
            {/* The button will execute the handler function set by the parent component */}
            <Button onClick={this.props.action.bind(this,param1)} />
        </div>
    )
} }

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android