[英]The value of the state is not updating in the following code using react and react-redux
首先,配置文件設置為默認值。 然后獲取數據,然后我嘗試將默認值設置為獲取的值
const Profile = () => {
const [profile, setProfile] = useState({
name3: "Naman Aggarwal",
username2: "_naman.agg",
bio2: "There's nothing holding me back, Nsut'23",
email2: "naman.aggarwal2001@gmail.com",
});
useEffect(() => {
fetch("http://localhost:5000/show")
.then((res) => res.json())
.then((res2) => {
console.log(res2.foundUser[0]);
setProfile((prevValue) => {
// console.log(profile);
const { name, username, bio, email } = res2.foundUser[0];
const { name3, username2, bio2, email2 } = profile;
return {
...prevValue,
[name3]: name,
[username2]: username,
[bio2]: bio,
[email2]: email,
};
});
// console.log(profile);
});
}, []);
}
我猜這個任務不起作用。
歡迎來到 StackOverflow!
我不完全理解手頭的問題,如果您能提供預期結果和實際結果會很有幫助,但我可以看到代碼中的 go 哪里出錯了。
在您的useEffect
function 中,您將返回以下 object:
return {
...prevValue,
[name3]: name,
[username2]: username,
[bio2]: bio,
[email2]: email,
};
現在,如果您希望 object 是{ name3: 'x', username2: 'y', bio2: 'z' }
那不會發生。 因為您沒有將 object 保存為這些值,所以您將每個鍵包裝在方括號[]
中,這意味着您正在應用其值,而不是按字面意思應用name3
username2
bio2
。
所以你會得到{ x: 'x', y: 'y', z: 'z' }
而不是{ name3: 'x', username2: 'y', bio2: 'z' }
z' } (基本上你會得到屬性的值而不是鍵名)。
我會嘗試修改返回 function 看起來像這樣:
return {
...prevValue,
name3: name,
username2: username,
bio2: bio,
email2: email,
};
如果我沒有發表評論,我希望我能解決問題,以便我們進一步討論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.