[英]Add key and value of object based on Array value
Iam working on a little project here, but i had some puzzle to do.我在这里做一个小项目,但我有一些难题要做。
So i had a state of react the value is like this所以我有一个 state 的反应值是这样的
const [dayValue, setDayValue] = useState({
monday: false,
tuesday: false,
wednesday: false,
thursday: false,
friday: false,
saturday: false,
sunday: false,
});
And then i had an array like this然后我有一个这样的数组
const arrayDays = ['monday', 'wednesday', 'saturday'];
What i want to do is to make all of my key object value that has the same value in arrayDays
to change the value become true
我想要做的是使我的所有关键 object 值在
arrayDays
中具有相同的值以更改值变为true
I already tried some methods, one of it is i implement it on useEffect like this我已经尝试了一些方法,其中之一是我像这样在 useEffect 上实现它
for (const x=0; x<arrayDays.length; x++) {
for (const key in dayValue) {
if (key === arrayDays[x]) {
setDayValue({
...dayValue,
[key]: true,
});
break;
}
}
}
but its not working because setState hooks is a async function *CMIIW.但它不起作用,因为 setState 挂钩是异步的 function *CMIIW。 does anyone know hot to solve this puzzle?
有谁知道热来解决这个难题?
Set the state using the functional update argument:使用功能更新参数设置 state:
setDayValue(dayValue => {
const updated = {...dayValue};
let needsUpdate = false;
for (const day of arrayDays) {
if (!(day in updated)) continue;
updated[day] = true;
needsUpdate = true;
}
return needsUpdate ? updated : dayValue;
});
var temp = {...dayValue};
arrayDays.forEach( day => {
if (temp[day] !== undefined) temp[day] = true;
})
setDayValue(temp);
Always try to use immutable data structures when updating state in react.在反应中更新 state 时,请始终尝试使用不可变数据结构。 So this is what i would recommend
所以这就是我推荐的
const arr = ['monday', 'wednesday', 'saturday'];
const updateDayValue = (arr) => {
const updated = {
...dayValue,
...arr.reduce((acc, cur) => {
return {
...acc,
[cur]: true
}
}, {})
}
setDayValue(updated)
}
I have written small piece of code for this one.我为此编写了一小段代码。 I could have written one liner but I choose to split my logic in small pieces for you understanding
我本可以写一个班轮,但我选择将我的逻辑分成小块以便你理解
const updateState = () => {
const stateClone = { ...dayValue };
const keyValueMap = Object.keys(stateClone).map((key) => ({
key,
value: stateClone[key]
}));
const updatedState = keyValueMap.reduce(
(acc, { key }) => ({ ...acc, [key]: arrayDays.includes(key) }),
{}
);
setDayValue(updatedState);
};
Also if you have any confusions you can go through this sandbox link: https://codesandbox.io/s/falling-wood-gflskr?file=/src/App.js:350-699此外,如果您有任何困惑,您可以通过此沙箱链接go:https://codesandbox.io/s/falling-wood-gflskr?file=/src/App.js:350-699
arrayDays.map(i => {
Object.keys(dayValue).map(n => {
if(i === n){
setDayValue(daysN => {
let days = {...daysN}
days[n] = true
return days
})
}
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.