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

react-router-dom v6传递state报错:Cannot read properties of undefined (reading 'state')

解决React Router 6中传递state时的TypeError问题

你的代码存在两个关键错误,导致了Cannot read properties of undefined (reading 'state')的报错,以下是具体修正方案:


错误1:导入路径拼写错误

Wallet组件中useNavigate的导入路径少了字母r,应该是react-router-dom而非react-route-dom,错误的导入会导致导航功能异常。

错误2:useLocation使用方式错误

useLocation()钩子直接返回的就是location对象,不需要再解构{ location },这种写法会让你拿到的location变量为undefined,进而读取state时触发报错。


修正后的代码

Wallet.js(发送方)

import { useNavigate } from "react-router-dom"; // 修正导入路径
const Wallet = ({ address, amount, symbol, destroy }) => {
  const navigate = useNavigate();
  return (
    <div>
      <button
        onClick={() => navigate("/booked", { state: { address } })} // 无需模板字符串,直接传递address即可
      >
        跳转至房间管理
      </button>
    </div>
  );
};

RoomManagement.js(接收方)

import { useLocation } from "react-router-dom";
const RoomManagement = () => {
  const location = useLocation(); // 直接接收location对象
  // 添加可选链判断,避免直接访问路由时state不存在的情况
  const address = location.state?.address;
  console.log("get address: ", address);
};

额外注意事项

  • 确保路由配置中/booked路径对应的组件是RoomManagement,否则导航后无法正确接收state;
  • 使用可选链操作符?.可以避免用户直接输入/booked地址时,因state不存在而触发新的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 19:48:44