【问题标题】:ReactJS, How to update the State of the PARENT from the CHILD [duplicate]ReactJS,如何从孩子更新父母的状态[重复]
【发布时间】:2018-10-19 12:05:25
【问题描述】:

如果我有一个设置状态并将其传递给子级的父级,我如何从子级更改父级的状态?

    // parent
    this.state = {
        status: 'doing...'
    }

    // child render
    <div>{this.props.state.status}</div>
    // child function triggered by an onClick
    update = () => this.setState(status: 'finished');

这样的东西是行不通的

    // parent
    this.state = {
        status: this.props.state.status
    }

    // or child
    this.props.setState(status: 'finished');

    // or child
    getDerivedStateFromProps(nextProps) {
       console.log('I'm never executed)
       this.setState({ status: nextProps.state.status});
    }

【问题讨论】:

    标签: javascript reactjs react-props


    【解决方案1】:

    这里说的

    How to update the state of child component from parent?

    使用选项 2,我不明白的是如何通过 props 传递函数。

    如果我在孩子中定义了&lt;CHILD message={this.message},那么我可以在孩子中使用this.props.message 调用该函数。

    【讨论】:

    • 是的,最好删除这个问题...:)
    • 是吗?我永远不知道在这些情况下该怎么做,它可能对未来的读者有用(我已经回答了我正在回答的问题,但现在我要到 2 天后才能标记它)
    • 那行得通……好吧……好伙伴! :)
    【解决方案2】:

    我们偶然发现了同样的问题。我们的做法是将原始状态更改器外包给父级本身。不要管理父组件和子组件之间的状态。如果需要,请使用 Redux 调度它。

    目前,我能说的最好的话是:

    // Parent Component
    class Parent {
      constructor(props) {
        super(props);
        this.state = {};
        this.handleClick = this.handleClick.bind(this);
      }
      handleClick() {
        this.setState({
          SomeVar: "Something"
        });
      }
      render() {
        <Child onUpdate={this.handleClick} />
      }
    }
    

    现在有了孩子,以这种方式发送值更容易。

    【讨论】:

    • 谢谢!我刚刚发布了对我有用的东西,最后很简单。无论如何,我还没有跳入 Redux :_)
    • @Gerard 哈哈...对你有好处...我们尝试实现它并无限陷入 Redux...大声笑。
    • @NguyễnThanhTú 谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 2015-06-14
    • 2014-05-14
    • 2018-03-19
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    相关资源
    最近更新 更多