父状态更改后更新子组件

问题描述 投票:0回答:2

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

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
2个回答
1
投票

你可以使用shouldComponentUpdate(nextProps,nextState)并返回true,如果父母改变了propsstate

More info in the react documentation


0
投票

替换componentWillReceiveProps的生命周期方法是static getDerivedStateFromProps。 (实际上这并不完全正确,但你可以用它来达到同样的效果) 该函数是静态的,接收组件的状态和props,并返回一个新对象以合并到组件的状态。

但真正的问题是 - 你真的需要吗?上述问题的答案(略有调整):

getDerivedStateFromProps(nextProps) {
  return nextProps.data;
}

什么都不做。你也可以使用道具而不是状态。 正如React doc所说:

此方法适用于罕见的用例,其中状态取决于道具随时间的变化。

© www.soinside.com 2019 - 2024. All rights reserved.