You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-router-dom v6页面跳转时State数据丢失问题

React Router DOM 页面间传递数组数据偶发字段丢失问题

使用react-router-dom的navigate方法在页面间传递数组数据时,出现偶发的部分字段丢失情况。

问题详情

传递数据的代码:

navigate("/CustomerInformation", { state: {petData: petDataArray }});

发送前打印petDataArray,显示两个完整对象:

[{"petObj":{"name":"Jaxon","breed":"Akita","comments":"Test","birthday":"20210811","gender":"Female","breeding":"Fully Functional"}},{"petObj":{"name":"Bo Champ","breed":"Akita","comments":"This is a test edit","birthday":"20210820","gender":"Female","breeding":"Spayed"}}]

但在目标页面的useEffect中打印location.state时,第二个对象的部分字段丢失:

[{"petObj":{"name":"Jaxon","breed":"Akita","comments":"Test","birthday":"20210811","gender":"Female","breeding":"Fully Functional"}},{"petObj":{"name":"","breed":"","comments":"This is a test edit","birthday":"","gender":"","breeding":"Spayed"}}]

可能原因及解决办法

  • 数据引用导致的意外修改
    如果petDataArray中的对象直接引用了表单或其他动态更新的数据源,navigate执行前可能有其他操作清空了部分字段。解决方式是传递前深拷贝数据,切断引用:

    const clonedPetData = petDataArray.map(item => JSON.parse(JSON.stringify(item)));
    navigate("/CustomerInformation", { state: {petData: clonedPetData }});
    
  • 状态序列化限制
    React Router传递state时会序列化数据,若对象包含不可序列化的属性(如函数、循环引用),会导致字段丢失。解决方式是确保数据为纯JSON结构,或先转为JSON字符串传递:

    // 发送页面
    const serializedData = JSON.stringify(petDataArray);
    navigate("/CustomerInformation", { state: {petData: serializedData }});
    
    // 目标页面
    useEffect(() => {
      if (location.state?.petData) {
        const petData = JSON.parse(location.state.petData);
        console.log(petData);
      }
    }, [location.state]);
    
  • 渲染时序问题
    目标页面的useEffect可能在location.state完全同步前执行,导致读取到不完整数据。解决方式是添加条件判断,确保数据完整后再处理:

    useEffect(() => {
      if (location.state?.petData && location.state.petData.length === 2) {
        console.log(location.state.petData);
      }
    }, [location.state]);
    

内容的提问来源于stack exchange,提问作者UndercoverGeek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 16:48:24