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

为什么使用props.location.state初始化useState得到的state变量为undefined

问题原因
  • 核心错误是useState返回值为数组,你使用了对象解构语法取值
    React 的useState钩子返回值是固定的长度为2的数组,第一个位置是状态变量,第二个位置是状态更新方法,必须使用数组解构才能正确拿到对应值。你写的{ myData, setMyData }属于对象解构,无法匹配到数组下标对应的属性,因此myData最终为undefined。

修复代码

export default function myFunc(props) {
  // 将对象解构替换为数组解构即可
  const [myData, setMyData] = useState(props.location.state);
  console.log('props here', props.location.state); // 可打印出预期的对象
  console.log('myData here', myData); // 此时可以正常输出预期对象
}

补充注意事项

如果存在用户直接访问该页面、或者刷新页面的场景,props.location.state会丢失变为undefined,可以给useState添加兜底初始值避免后续调用报错,示例如下:

const [myData, setMyData] = useState(props.location.state ?? {});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:15:03