【问题标题】:Reactjs - update child component state when parent component state changesReactjs - 当父组件状态改变时更新子组件状态
【发布时间】:2021-06-08 13:26:36
【问题描述】:

我是 reactjs 新手,我不知道如何从父组件更改子组件状态。下面是代码

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

只要在父组件中的productCode 上完成setState,我希望子组件接收productCode。

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

有什么建议吗?

【问题讨论】:

标签: reactjs


【解决方案1】:

这确实有效,但请注意 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>

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      像这样继续:首先在父组件中编写一个更改其状态的函数,然后将该函数交给子组件,然后在子组件中调用该函数。这是一个代码示例,您可能会稍微摆弄一下:

      // 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}
            />
         )
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-05
        • 2017-07-10
        • 2015-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多