为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我的状态迭代被覆盖了?

为什么我的状态迭代被覆盖了?

墨色风雨 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 关注
  • 97 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信