React Router v6类组件跳转时如何传递并生效新状态?
解决React Router v6类组件跳转传state并生效的方案
1. 跳转时正确传递state
在你的表单类组件中,请求到新数据后,调用navigate时要把数据放在state字段内,示例代码如下:
import { withNavigate } from 'react-router-dom'; class FormComponent extends React.Component { handleSubmit = async (e) => { e.preventDefault(); // 请求新数据 const newData = await fetchNewData(); // 跳转并携带新数据作为state this.props.navigate('/store', { state: { storeData: newData // 自定义字段名,方便目标页面识别 } }); }; // 其他组件逻辑... } export default withNavigate(FormComponent);
2. 给目标页面封装获取location的高阶组件
React Router v6没有内置withRouter,需要自己封装withLocation高阶组件,让类组件能拿到路由的location对象:
import { useLocation } from 'react-router-dom'; const withLocation = (Component) => { return (props) => { const location = useLocation(); return <Component {...props} location={location} />; }; }; export default withLocation;
3. 目标页面处理传递的state并更新渲染
在/store对应的类组件中,通过高阶组件拿到location后,在组件挂载和路由更新时检查location.state,存在新数据就替换初始状态:
import React from 'react'; import withLocation from './withLocation'; class StorePage extends React.Component { state = { data: initialData // 应用挂载时的初始数据 }; componentDidMount() { this.updateDataFromState(); } componentDidUpdate(prevProps) { // 路由变化时(比如从表单跳转过来),重新检查state if (this.props.location !== prevProps.location) { this.updateDataFromState(); } } updateDataFromState = () => { const { state } = this.props.location; if (state?.storeData) { // 用传递的新数据更新组件状态 this.setState({ data: state.storeData }); } }; render() { const { data } = this.state; // 基于最新data渲染页面 return <div>{/* 你的渲染逻辑 */}</div>; } } export default withLocation(StorePage);
关键注意事项
- 传递state必须放在
navigate第二个参数的state属性中,不能直接传参。 - 目标页面要监听
location变化:如果之前访问过/store,跳转回来时componentDidMount不会触发,必须在componentDidUpdate中检查路由变化。 - 首次访问
/store时,componentDidMount会触发,可直接读取location.state中的数据。
内容的提问来源于stack exchange,提问作者user14398375
相关产品推荐
相关产品推荐

