首页 > 解决方案 > 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

标签: reactjsreact-context

解决方案


推荐阅读