[英]How do I compare two arrays of objects to see if they have the same ids and then return another value from the matching object?
[英]How to compare two objects value by iterating if both have same name in getDerivedStateFromProps?
The props coming from react is account and I'm keeping a copy of it as previousProps, before setting it to the state I need to compare each and every object and assign the value to state if both props object are different. 但是,之前的道具和 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],
},
};
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.