说我有这个 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/