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

React中通过NavLink传递state属性获取失败问题求助

react-router-dom v6传递state后获取不到的问题

我正在自学React(版本v18.1.0),使用react-router-dom v6.3.0时遇到一个问题:无法获取通过NavLink传递给组件的属性,得到的是undefined。

我的代码情况

触发跳转的NavLink代码:

[...]
{
   var1 != null
   ?
   <NavLink className="Menu-Button" to={{pathname : "/Component1"}} state = {{ props : var1 }}>ButtonContent</NavLink>
   : <p/>
}
[...]

目标组件Component1代码:

import React from 'react';
import {useLocation} from 'react-router-dom';

const Component1= () => {

    const location = useLocation();
    const { props } = location;
    console.log(props);

    return(
    [...]
    )
};

export default Component1;

console.log输出为undefined,尝试用props.location替代useLocation()结果一样。

补充App.js路由配置:

[all the imports]

const App = () => {
  return (
     <BrowserRouter>
       <Toolbar />
       <Routes>
         [all the existing routes that work fine]
         <Route exact path='/Component1' element={<Component1 /> } />
       </Routes>
     </BrowserRouter>
  );
}

export default App;

问题原因及解决方法

问题出在state的读取路径上:react-router-dom v6中,通过NavLink的state属性传递的数据,会被存放在location.state对象里,而不是直接挂载在location根对象下。

修改Component1的代码,调整state的读取方式即可:

import React from 'react';
import {useLocation} from 'react-router-dom';

const Component1= () => {
    const location = useLocation();
    // 先解构state,添加默认空对象避免无state时报错
    const { props } = location.state || {};
    console.log(props);

    return(
    [...]
    )
};

export default Component1;

解释:

  • 当通过NavLink的state传值时,数据会被包裹在location.state中,所以必须从这个嵌套对象里解构你需要的属性
  • 添加|| {}是为了防止用户直接访问/Component1路由(没有通过NavLink跳转)时,location.state为undefined导致解构报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:20:37