如果两个对象在 getDerivedStateFromProps 中具有相同的名称,如何通过迭代来比较两个对象的值?
How to compare two objects value by iterating if both have same name in getDerivedStateFromProps?
来自 react 的 props 是 account,我保留了它的副本作为 previousProps,在将其设置为状态之前,我需要比较每个对象并将值分配给 state(如果两个 props 对象不同) .但是,previous props 和 redux props 都是同类的。有什么方法可以遍历它而不是在下面一一写。
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],
},
};
}
});
来自 react 的 props 是 account,我保留了它的副本作为 previousProps,在将其设置为状态之前,我需要比较每个对象并将值分配给 state(如果两个 props 对象不同) .但是,previous props 和 redux props 都是同类的。有什么方法可以遍历它而不是在下面一一写。
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],
},
};
}
});