如何明确替换 componentWillReceiveProps 并不断获取 nextProps?
Posted
技术标签:
【中文标题】如何明确替换 componentWillReceiveProps 并不断获取 nextProps?【英文标题】:How to definitely replace componentWillReceiveProps and keep getting the nextProps? 【发布时间】:2019-07-31 11:08:16 【问题描述】:我在我的应用程序中运行 React 16.8.4,在某些情况下我确实需要使用 nextProps。正如 React Docs 提到的,componentWillReceiveProps 是一种不安全的方法,不建议再使用它。 我阅读了文档 (https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key),但我什至不知道如何使用带有键和所有内容的此版本移植我的旧 componentWillReceiveProps。 我不需要创建一个新的组件实例,我只需要 nextProps ! 我尝试使用 componentDidUpdate(),但我不想获取 prevProps,我想要 NEXT PROPS! 你们能帮忙吗?
【问题讨论】:
【参考方案1】:componentDidUpdate
中的this.props
与componentWillReceiveProps
中的nextProps
相同,因此您可以使用它。
// componentWillReceiveProps(nextProps)
// if (nextProps.someProp !== this.props.someProp)
// doSomething();
//
//
componentDidUpdate(prevProps)
if (this.props.someProp !== prevProps.someProp)
doSomething();
【讨论】:
【参考方案2】:您可以使用getDerivedStateFromProps
代替componentWillReceiveProps
。
【讨论】:
以上是关于如何明确替换 componentWillReceiveProps 并不断获取 nextProps?的主要内容,如果未能解决你的问题,请参考以下文章