在 redux 中的 react 16 中替换组件 WillRecieiveProps?



说我有这个缩减器,它将我的工作状态从"待处理"更改为"批准",

如何在不使用将要弃用componentWillRecieiveProps的情况下使用它?

我曾经这样做过

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存储在本地状态中,称为jobStatus布尔值,然后仅在this.state.jobStatus为真时在我的渲染中询问this.props.job对象。

如果这样做,那么您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应该是一个纯函数并且没有副作用,我已经更新了片段以反映这一点。

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

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

最新更新