亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我的狀態迭代被覆蓋了?

為什么我的狀態迭代被覆蓋了?

墨色風雨 2023-06-09 14:46:02
嗨,所以我不確定為什么我的掛鉤中的項目被覆蓋并且只有最后一個值保留在其中。直到我循環遍歷 xml 為止,一切正常。鉤子setCampgrounds()沒有保存所有迭代。我本以為...campgrounds傳播會復制上一次迭代,這樣它就不會被覆蓋。循環中有什么我不理解的東西,或者將這些項目保存在我的露營地掛鉤中的正確方法是什么?const [campgrounds, setCampgrounds] = useState([]);    useEffect(() => {        url = some url...        axios.get(url)            .then(res => res.data)            .then((str) => {                let newXML = new DOMParser().parseFromString(str, "text/xml");                let results = newXML.getElementsByTagName("result");                for (let i = 0; i < results.length; i++) {                    setCampgrounds([...campgrounds, {                        facilityID: results[i].getAttribute("facilityID"),                         facilityName: results[i].getAttribute("facilityName"),                        contractID: results[i].getAttribute("contractID")                    }]);                   }            })            .catch(err => {                console.log(err);            })                }, []);
查看完整描述

1 回答

?
阿波羅的戰車

TA貢獻1862條經驗 獲得超6個贊

問題

campgrounds對于您要排隊的每個狀態更新,當前狀態值都是相同的,因此每個更新都會被下一個更新覆蓋,最后一個設置狀態的更新是持續存在的更新。

解決方案

使用功能狀態更新對每個更新進行排隊。每個入隊更新都使用前一個更新的結果狀態。

功能更新

const [campgrounds, setCampgrounds] = useState([]);


...


for (let i = 0; i < results.length; i++) {

? setCampgrounds(campgrounds => [

? ? ...campgrounds,

? ? {

? ? ? facilityID: results[i].getAttribute("facilityID"),

? ? ? facilityName: results[i].getAttribute("facilityName"),

? ? ? contractID: results[i].getAttribute("contractID")

? ? }

? ]);

}


查看完整回答
反對 回復 2023-06-09
  • 1 回答
  • 0 關注
  • 171 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號