javascript - 在 redux 的 React 16 中替换 componentWillRecieiveProps?

标签 javascript reactjs redux react-16

说我有这个 reducer 将我的工作状态从“待定”更改为“批准”,

如何在不使用即将弃用的 componentWillRecieiveProps 的情况下处理它?<​​/p>

我曾经这样做过

componentWillRecieiveProps(prevProps, nextProps) {
  if (prevProps.job.status !== nextProps.job.status && nextProps.job.state === 'approved') {
    this.props.history.replace('somewhere')
  }
}

最佳答案

@Shishir Anshuman 的评论是正确的,您应该使用 getDerivedStateFromProps ,但具体方法并不是很明显,所以我将向您展示。

这是您比较 prevProps 和 nextProps 的原始代码段:

componentWillRecieiveProps(prevProps, nextProps) {
  if (prevProps.job.status !== nextProps.job.status && nextProps.job.state === 'approved') {
    this.props.history.replace('somewhere')
  }
}

它应该是这样的:

static getDerivedStateFromProps(nextProps, prevState) {
  if (prevState.job.status !== nextProps.job.status && nextProps.job.state === 'approved') {
    // return new object to update state
  }
  return null;
}

这是基于您正在存储 job.status 的假设在本地状态,所以你的组件的构造需要看起来像这样:

constructor(props) {
  super(props);

  this.state = {
    job: props.job,
  };
}

尽管鉴于我无法完全了解您的数据结构,但我可能会存储 job.status在本地状态中作为 bool 值称为 jobStatus , 然后只询问 this.props.job this.state.jobStatus 时我渲染中的对象是真的。

如果你这样做,那么你的 getDerivedStateFromProps看起来像这样:

static getDerivedStateFromProps(nextProps, prevState) {
  if (prevState.jobStatus !== nextProps.job.status && nextProps.job.state === 'approved') {
    // return new object to update state
  }
  return null;
}

编辑 1

正如@Patrick Hund 在评论中指出的那样,我在 getDerivedStateFromProps 之前错过了 static 关键字。方法,这是必需的。

编辑2

正如@markerikson 在下面的评论中正确指出的那样 getDerivedStateFromProps应该是一个纯函数并且没有副作用,我已经更新了代码片段以反射(reflect)这一点。

这是我没有完全理解的文档中的重要句子:

It should return an object to update state, or null to indicate that 
the new props do not require any state updates.

关于javascript - 在 redux 的 React 16 中替换 componentWillRecieiveProps?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49983063/

相关文章:

reactjs - 错误 : useRoutes() may be used only in the context of a <Router> component

reactjs - React的`this.props`里面的`getDefaultProps()`?

redux - 构建状态管理存储(ngrx/redux)。平面代表数据,还是嵌套代 TableView ?

javascript - 在线条动画之后向折线图数据点添加工具提示

javascript - 在链接中放置 AJAX 相关内容的正确位置是什么

javascript - Vue.js Avoriaz 单元测试在使用 vue-i18n 时产生翻译警告

使用唯一 ID 进行 Javascript 测试

javascript - 迭代完成之前回调触发

javascript - 从 TypeScript 生成 PropType

react-native - 清除或调用操作来重置状态?