如何明确替换 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.propscomponentWillReceiveProps 中的nextProps 相同,因此您可以使用它。

// componentWillReceiveProps(nextProps) 
//   if (nextProps.someProp !== this.props.someProp) 
//     doSomething();
//   
// 

componentDidUpdate(prevProps) 
  if (this.props.someProp !== prevProps.someProp) 
    doSomething();
  

【讨论】:

【参考方案2】:

您可以使用getDerivedStateFromProps 代替componentWillReceiveProps

【讨论】:

以上是关于如何明确替换 componentWillReceiveProps 并不断获取 nextProps?的主要内容,如果未能解决你的问题,请参考以下文章

oracle sql语句中的替换问题

什么时候应该明确使用 StringBuilder? [复制]

如何清理复选框?

页面没有跟随Vue中数组元素的替换动态展示

sed命令

正则表达式搜索+替换 href="URL"