gpt4 book ai didi

Can't get UseEffect() to set State properly with spreader(无法让UseEffect()正确设置散布器的状态)

转载 作者:bug小助手 更新时间:2023-10-26 20:11:39 26 4
gpt4 key购买 nike



I'm working on a project in react using graphql. I have an object

我正在做一个使用GraphQL的Reaction项目。我有一件物品


const [additionalInfo, setAdditionalInfo] = useEffect({}),

Const[添加信息,设置添加信息]=useEffect({}),


which contains objects that have been selected. On this screen, I have data that is coming from my backend, which looks like: {status: "single", work:"full-time", etc...} that I need to add to my additionalInfo object if it contains a "!" (signifies that it was previously selected). I've been trying to do this using a useEffect, but I'm having some issues.

其中包含已选择的对象。在这个屏幕上,我有来自我的后端的数据,它看起来像:{Status:“Single”,Work:“Full-time”等...}如果它包含“!”,我需要添加到我的附加Info对象中。(表示它以前被选中)。我一直在尝试使用useEffect来完成此操作,但我遇到了一些问题。


useEffect(()=> {
for (var item in meDataData?.lifeStyle) {
if ( meDataData?.lifeStyle[item]?.includes('!')) {
setAdditionalInfo(
....additionalInfo,
[item]: meDataData?.lifeStyle[item]?.substring(0,
meDataData?.lifeStyle[item]?.length - 1)
})
}
}
}, [meDataData?.lifeStyle])

where meDataData?.lifeStyle = {status: "single!", work:"full time!", dependents:"none", "higherEducation": null,}only gives me additionalInfo = {work:"full time"}. After searching for solutions and answers for why the spreader wasn't working I tried:

其中meDataData?.life Style={Status:“Single!”,Work:“Full Time!”,受抚养人:“None”,“HigherEducation”:空,}只给我额外的Info={Work:“Full Time”}。在寻找了解决方案和答案来解释为什么撒布器不起作用后,我试了试:


 useEffect(()=> {
for (var item in meDataData?.lifeStyle) {
if ( meDataData?.lifeStyle[item]?.includes('!')) {
setAdditionalInfo(prevState =>{
return ({
...prevState,
[item]: meDataData?.lifeStyle[item]?.substring(0, meDataData?.lifeStyle[item]?.length - 1)
})
})
}
}
}, [meDataData?.lifeStyle])

which gave me additionalInfo = {status:"single", higherEducation:undefined}. Does anyone know why I am having this problem? I would really appreciate any help or advice on how to solve this problem. Thank you!

这给了我additionalInfo = {status:“single”,higherEducation:undefined}。有人知道我为什么会有这个问题吗?我真的很感激任何帮助或建议如何解决这个问题。谢谢大家!


更多回答
优秀答案推荐

Create a new object and update it inside the loop before setting it into the state after the loop.

创建一个新对象并在循环中更新它,然后将其设置为循环后的状态。


const newInfo = {...additionalInfo};
for (const [key, val] of Object.entries(meDataData?.lifeStyle ?? {}))
if (val?.includes('!'))
newInfo[key] = val.slice(0, -1);
setAdditionalInfo(newInfo);

更多回答

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com