react-router v3中如何为所有子路由配置并共享同一Context上下文
react-router v3 全局上下文Provider配置方案
要实现所有子路由共享同一个Context实例,直接在根路由层挂载带Provider的包装组件即可,react-router v3 中子路由匹配到的组件会自动作为父路由组件的children属性传入,天然支持嵌套包裹:
步骤1:实现根路由包装组件
创建一个根组件,在组件内封装你的ContextProvider逻辑:
import { YourContextProvider } from './你的context文件路径'; // 如果需要保留原有的Layout组件也可以在此处引入 import Layout from './你的Layout组件路径'; const RootWrapper = ({ children }) => { // 此处定义你需要共享的全局状态、方法 const sharedState = { // 你的全局状态 }; const sharedMethods = { // 你的全局方法 }; return ( <YourContextProvider value={{ ...sharedState, ...sharedMethods }}> {/* 保留原有Layout的话把children放在Layout内部即可 */} <Layout> {/* children为react-router自动传入的匹配到的子路由组件 */} {children} </Layout> </YourContextProvider> ); }; export default RootWrapper;
步骤2:修改根路由配置
给你的根路由新增component属性绑定上面写的RootWrapper:
import RootWrapper from './RootWrapper'; { path: "/", component: RootWrapper, // 新增该行配置 getChildRoutes(_: LocationState, cb: RoutesCallback) { const routes = require("./routes").default; cb(null, routes()); }, }
说明
- 该方案下所有通过
getChildRoutes动态加载的子路由都会被同一个ContextProvider包裹,所有子路由组件都可以直接消费同一个上下文实例,路由切换时上下文状态会持久保留不会重置。 - 如果需要根据路由参数更新上下文值,直接在
RootWrapper中通过react-router v3注入的location、params等props触发状态更新即可。
内容的提问来源于stack exchange,提问作者Mahen Gandhi
相关产品推荐
相关产品推荐

