React中为不同路由配置独立Context时仅首个路由生效如何解决
问题根因
你的代码问题出在对Switch组件的特性使用错误。Switch组件的核心逻辑是:仅渲染第一个与当前访问路径匹配的直接子元素。你当前把Context.Provider作为Switch的直接子节点,而Provider本身没有path属性,Switch会默认它匹配所有路径,所以不管你访问什么路由,都会直接渲染第一个GlobalTimerProgramContext.Provider节点,后面的所有Provider、路由都不会被触发渲染,这就是只有第一个路由能正常工作的原因。
修复方案
有两种常用的实现方式:
方案1:在Route的render属性中嵌套Provider
保证Switch的直接子节点都是Route组件,让路径匹配逻辑正常生效:
<Router> <Switch> <Route strict exact={true} path="/programs" render={(props) => ( <GlobalTimerProgramContext.Provider value={{ globalPrograms, setGlobalPrograms }} > <ProgramsOverview {...props} /> </GlobalTimerProgramContext.Provider> )} /> <Route strict exact={true} path="/profiles" render={(props) => ( <GlobalProfileContext.Provider value={{ globalProfiles, setGlobalProfiles }} > <ProfilesOverview {...props} /> </GlobalProfileContext.Provider> )} /> <Route strict exact={true} path="/channels" render={(props) => ( <GlobalChannelContext.Provider value={{ globalChannels, setGlobalChannels }} > <ChannelsOverview {...props} /> </GlobalChannelContext.Provider> )} /> <Route strict path="/" exact={true}> <Redirect to="/programs" /> </Route> </Switch> </Router>
方案2:用Route直接包裹Provider和对应组件
把Provider放在Route的子节点内,同样保证Switch的直接子节点都是可匹配的Route:
<Router> <Switch> <Route strict exact={true} path="/programs"> <GlobalTimerProgramContext.Provider value={{ globalPrograms, setGlobalPrograms }} > <ProgramsOverview /> </GlobalTimerProgramContext.Provider> </Route> <Route strict exact={true} path="/profiles"> <GlobalProfileContext.Provider value={{ globalProfiles, setGlobalProfiles }} > <ProfilesOverview /> </GlobalProfileContext.Provider> </Route> <Route strict exact={true} path="/channels"> <GlobalChannelContext.Provider value={{ globalChannels, setGlobalChannels }} > <ChannelsOverview /> </GlobalChannelContext.Provider> </Route> <Route strict path="/" exact={true}> <Redirect to="/programs" /> </Route> </Switch> </Router>
内容的提问来源于stack exchange,提问作者bbasmer
相关产品推荐
相关产品推荐

