简体   繁体   English

父状态更改后更新子组件

[英]Updating a child component after the parent state changes

This question has already been answered here but things are always changing. 这里已经回答这个问题但情况总是在变化。

componentWillReceiveProps is deprecated now and it will be removed soon. componentWillReceiveProps现在已过时,它将很快被删除。
So, what is the cleanest way to update a child component when the parent needs to fetch some data? 那么,当父级需要获取一些数据时,更新子级组件的最干净方法是什么?

See the old question for more details. 有关更多详细信息,请参见旧问题。
Thanks 谢谢

UPDATE: 更新:

Basically, the parent component fetches some data and the child component needs that data. 基本上,父组件会获取一些数据,而子组件则需要该数据。

This is the child component. 这是子组件。

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

You can use the shouldComponentUpdate(nextProps,nextState) and return true if the props or state changed in the parent. 您可以使用shouldComponentUpdate(nextProps,nextState)并在父项中的propsstate更改时返回true

More info in the react documentation React文档中的更多信息

The lifecycle method that replaced componentWillReceiveProps is static getDerivedStateFromProps . 替换componentWillReceiveProps的生命周期方法是static getDerivedStateFromProps (Actually that's not entirely true, but you can achieve the same result with it) (实际上这并不完全正确,但是您可以用它达到相同的结果)
The function is static, and receives the state and props of the component, and returning a new object to merge into the component's state. 该函数是静态的,并接收组件的状态和属性,并返回一个新对象以合并到组件的状态。

But the real question is - do you really need it? 但是真正的问题是-您真的需要吗? The answer from the question above (slightly adjusted): 上面问题的答案(略有调整):

getDerivedStateFromProps(nextProps) {
  return nextProps.data;
}

simply does nothing. 根本什么也没做。 You can just as well use the props instead of the state. 您也可以使用道具代替状态。
As the React doc says: 正如React文档所说:

This method exists for rare use cases where the state depends on changes in props over time. 此方法适用于状态依赖于道具随时间变化的罕见用例。

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

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