首页 > 解决方案 > 在父状态更改后更新子组件

问题描述

这个问题已经在这里得到了回答,但事情总是在变化。

componentWillReceiveProps现在已弃用,很快将被删除。
那么,当父组件需要获取一些数据时,更新子组件的最简洁方法是什么?

有关更多详细信息,请参阅旧问题。
谢谢

更新:

基本上,父组件获取一些数据,而子组件需要这些数据。

这是子组件。

class Dropdown extends React.Component {
constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
}


// This is deprecated so need to be replaced by your answer
componentWillReceiveProps(nextProps) {
    this.setState({
        value: nextProps._layouts[0]
    });
}


handleChange(event) {
    this.setState({
        value: event.target.value
    });
}

render() {
    // The options for the dropdown coming from the parent
    const options = this.props._layouts.map((number) =>
        React.createElement("option", null, number)
    )

    // This logs the value coming from the parent
    // A timeout is needed since fetch is asynchronous
    setTimeout(() => {
        console.log(this.state.value)
    }, 400);

    // This is just a dropdown menu
    return React.createElement("div",
        null, React.createElement("span", {
            class: "custom-dropdown"
        }, React.createElement("select", {
            onChange: this.handleChange,
        }, options)));
    }
}

标签: reactjs

解决方案


如果父项中的或更改,您可以使用shouldComponentUpdate(nextProps,nextState)和返回。truepropsstate

反应文档中的更多信息


推荐阅读