React函数组件中如何访问react-router(v5)传递的state?
React Router v5 函数组件中访问路由传递的state
你通过history.push的state字段传递数据的写法是对的,但目标页面是函数组件,不能用this.state来获取路由state,得用React Router提供的useLocation钩子。
具体解决步骤:
- 从
react-router-dom导入useLocation钩子 - 在组件中获取
location对象,从中取出传递的state - 处理
state可能为undefined的场景(比如用户直接访问目标路由,而非通过跳转进入)
修改后的目标页面代码:
import { useParams, useLocation } from 'react-router-dom'; // 新增useLocation导入 import { useEffect } from 'react'; export default function Symgraph(props) { useEffect(() => { }, []); const { sym } = useParams(); const location = useLocation(); // 获取location对象 const id = location.state?.id; // 用可选链避免state为undefined时报错 return ( <div className='main-chart mb15' > <ThemeConsumer> {({ data }) => { return data.theme === 'light' ? ( <AdvancedChart widgetProps={{ theme: 'light', symbol: 'OKBUSDT', allow_symbol_change: false, toolbar_bg: '#fff', height: 550, details: 'true', style: '3', }} /> ) : ( <AdvancedChart widgetProps={{ theme: 'dark', symbol: 'OKBUSDT', allow_symbol_change: false, toolbar_bg: '#000', height: 550, details: 'true', style: '3', }} /> ); }} </ThemeConsumer> <h1>{sym}, {id}</h1> {/* 替换原来的this.state.id */} </div> ) }
补充注意:
- 路由传递的
state存在内存中,如果用户直接刷新目标页面,state会丢失。要是需要数据持久化,建议把参数放到URL路径或查询参数里。 - 用
location.state?.id的可选链操作符,是防止用户直接访问/${sym}路由时,location.state为undefined导致报错,你也可以给id加默认值,比如const id = location.state?.id || '默认ID'。
内容的提问来源于stack exchange,提问作者user10969500
相关产品推荐
相关产品推荐

