reactjs - React Context Provider does not update the value when it is in a Router Switch
问题描述
const Context = React.createContext("initial")
Here is the JSX code.
<Router>
<Switch>
<Route exact path="/a">
<Context.Provider value="updated">
<A/>
</Context.Provider>
</Route>
<Route exact path="/b">
<B/>
</Route>
</Switch>
</Router>
Here Component A is a child of context provider. But when the Consumer takes the context, the value is still "initial".
class A extends Component {
...
render() {
return (
<Context.Consumer>
{context => (
<div>
<p> value is {context}</p>
</div> ) }
</Context.Consumer>
)}
But if the Context Provider runs before Router, Consumer gives "updated" which is fine.
<Context.Provider value="updated">
<A/>
</Context.Provider>
<Router>
<Switch>
<Route exact path="/a">
<A/>
</Route>
<Route exact path="/b">
<B/>
</Route>
</Switch>
</Router>
The problem is why the value of Context is not updated to "updated" in first case
解决方案
推荐阅读
- python - 查找一个月内同一个人的两个地理编码之间的距离
- vue.js - “列表处于活动状态时如何添加左边框?”
- x-frame-options - 为什么chrome会忽略X-frame-option:sameorigin?
- c# - 使用自定义 PageStatePersister 时如何修复 Viewstate 中缺少的 DataKey
- ios - 应用程序恢复后 URLSession 代表不工作
- material-design - CoordinatorLayout 中的 Material FloatingActionButton 未显示在设计预览窗口中
- c# - Oracle Dll 加载错误:无法在另一台机器上运行 C# 控制台应用程序
- web-services - Navision OData 服务过滤器不起作用
- mysql - 如果项目没有序列号,则设置 sum(count),如果有序列号,则设置 1
- jenkins - Jenkins 项目版本控制