【问题标题】:Updating a child component after the parent state changes在父状态更改后更新子组件
【发布时间】:2019-07-12 04:26:40
【问题描述】:

这个问题已经回答了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.org/docs/react-component.html#updating
  • Re “请参阅旧问题了解更多详细信息。”,您的问题应该是独立的,而不是依赖于任何其他问题。如果另一个问题被关闭怎么办?如果您的问题需要更多详细信息,请嵌入它们而不是链接到其他地方。
  • @skomisa 我更新了答案。请告诉我是否需要更改任何内容。

标签: reactjs


【解决方案1】:

如果 propsstate 在父级中更改,您可以使用 shouldComponentUpdate(nextProps,nextState) 并返回 true

More info in the react documentation

【讨论】:

    【解决方案2】:

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

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

    getDerivedStateFromProps(nextProps) {
      return nextProps.data;
    }
    

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

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

    【讨论】:

    • componentWillReceiveProps 让我设置状态,而static getDerivedStateFromProps 没有。不使用componentWillReceiveProps如何设置状态?
    • this.state = {value: props.value} 在构造函数中工作得很好,但被认为是反模式,所以我使用了现在已弃用的componentWillReceiveProps
    • 使用getDerivedStateFromProps,你返回的值将与状态合并。无需自己致电this.setState()
    • 似乎没有:当记录 componentWillReceiveProps 给我我期望的更新道具时,getDerivedStateFromProps 给我undefined
    • 你能提供你实现getDerivedStateFromProps的方式吗?
    猜你喜欢
    • 1970-01-01
    • 2021-07-17
    • 2021-07-07
    • 2017-05-05
    • 1970-01-01
    • 2016-10-02
    • 2019-12-23
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多