如果两个对象在getDerivedStateFromProps中具有相同的名称,如何通过迭代来比较它们的值



来自react的道具是account,我将其作为previousProps保存一份副本,在将其设置为状态之前,我需要比较每个对象,并在两个道具对象不同的情况下将值分配给state。然而,之前的道具和redux道具都是同类的。有没有什么方法可以迭代它,而不是在下面一个接一个地写。

static getDerivedStateFromProps(nextProps: Props, prevState: State) {
console.log("getDerivedStateFromProps");
Object.keys(nextProps.account).every((key) => {
// can i compare both keys with a loop.
if (nextProps.account.firstName !== prevState.previousProps.firstName) {
console.log("different");
return {
previousProps: nextProps,
userInfo: nextProps,
personalInfo: {
first_name: nextProps.account.firstName,
},
};
}
});
if (nextProps.account.firstName !== prevState.previousProps.firstName) {
console.log("different");
return {
previousProps: nextProps,
userInfo: nextProps,
personalInfo: {
first_name: nextProps.account.firstName,
},
};
}
if (nextProps.account.lastName!== prevState.previousProps.lastName) {
console.log("different");
return {
previousProps: nextProps,
userInfo: nextProps,
personalInfo: {
last_name: nextProps.account.lastName,
},
};
}
return null;
}

我想你可以这样做;

Object.keys(nextProps.account).every((key) => {
if (nextProps.account[key] !== prevState.previousProps[key]) {
return {
previousProps: nextProps,
userInfo: nextProps,
personalInfo: {
[key]: nextProps.account[key],
},
};
}
});

相关内容

  • 没有找到相关文章

最新更新