繁体   English   中英

Reactjs - 当父组件 state 更改时更新子组件 state

[英]Reactjs - update child component state when parent component state changes

我是 reactjs 的新手,我无法弄清楚如何从父组件更改子组件 state。 下面是代码

<ChildComponent productCode={this.state.productCode} />

每当在父组件中的productCode上完成setState时,我希望子组件接收productCode

从父组件发布事件并在子组件中订阅事件是我的头等大事。

有什么建议么?

这确实有效,但请注意Child作为prop接收此数据,而不是作为其内部state的一部分。

 class Parent extends React.Component { constructor(props) { super(props); this.state = { count: 0, }; } render() { return ( <section> Count: {this.state.count} <br /> <button onClick={() => this.setState((prevState) => ({ count: prevState.count + 1, })) } > Increment Count </button> <Child passedCount={this.state.count} /> </section> ); } } class Child extends React.Component { render() { return ( <section> I am the child. The <code>count</code> * 2 ={' '} {/* Access `this.props.passedCount` to use the value */} <b>{this.props.passedCount * 2}</b> </section> ); } } const rootElement = document.getElementById('root'); ReactDOM.render(<Parent />, rootElement);
 section { background: beige; padding: 1em; } section > section { background: sandybrown; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

假设childState是您的孩子 state,如果您正在使用 class 组件,您必须向 class 添加一个componentWillReceiveProps挂钩生命周期。

componentWillReceiveProps(nextProps) {
  this.setState({ childState: nextProps.productCode});  
}

您已经完全了解人们使用 state 容器的原因。 我只能建议尝试 redux、mobx 或 mobx-state-tree。

如果你真的不想深入研究这些工具,事情会变得有点棘手,如果你坚持的话,无论如何你都可以这样做,但我建议不要这样做。

Proceed like this: first write a function in the parent that alters it state, then hand that function over to the child component, after that call that function in the child. 这是一个代码示例,您可能会稍微摆弄一下:

// the parent
function parent() {
   const [state, setState] = useState('')

   const update = () => {
      setState("new state")
   }

   return(<Child updateFunction={update} />)
}

// the cild
function Child(props) {
   return(
      <FancyComponent
         onClick={props.update}
      />
   )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM