React Context不更新路由器渲染路径

时间:2020-09-22 16:40:39

标签: javascript reactjs react-router state react-context

我无法弄清楚为什么提供给Navbar组件的上下文在这里可以工作,但是状态更改时路由中的页面不会更新。

我希望能够将此上下文传递给路由器中的所有页面以及诸如导航栏之类的所有组件。

传递上下文并从导航栏调用功能可以正常工作,并且导航栏会更新,但是没有相应的组件会更新。

mainApp是使用者,提供者上下文在APP中

import { AuthContext } from './auth';


class MainApp extends React.Component {

  static contextType = AuthContext

  constructor(props) {
    super(props);
    this.state = {
    };
  }

  componentDidMount(){
    const user = this.context 

  }
componentDidUpdate(){console.log(this.state);}

  render(){

    const user = this.context

  return (
    


    <div className="App-wrapper" key="mtgLynx">
   
    <Router>
    <div>
    <SiteNavBar  loginStatus={user.loggedIn} globalLogout={user.globalLogout} globalLogin={user.globalLogin} ></SiteNavBar>
     <Route exact path="/" component={Home} />
     <Route path="/articles" component={Articles} />
     <Route path="/links" render={(props) => <Links loginStatus={user.loggedIn}/>} />
     <Route path="/login" render={(props) => <Login loginStatus={user.loggedIn}/>} />
     <Route path="/createLink" render={(props) => <CreateLink loginStatus={user.loggedIn}/>} />
     <Route path="/topLinks" render={(props) => <TopLinks loginStatus={user.loggedIn}/>} />
     </div>
  
     </Router>
    </div>

  );
  }
}

export default MainApp;

这是App

import { AuthContext } from './auth';

import { createContext, useContext } from 'react';
import MainApp from './MainApp';

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      globalLoginStatus:false,
      counter:"0",   
      value:{username:"Guest",loginStatus:false
    }

    };

   this.globalLogout = this.globalLogout.bind(this);
  }
componentDidUpdate(){console.log(this.state);}


 globalLogout = () => {
 this.setState({globalLoginStatus:false,
 
}, 
  () => {console.log(this.state.globalLoginStatus)});
};

globalLogin = () => {
  this.setState({globalLoginStatus:true
  
 }, 
   () => {console.log(this.state.globalLoginStatus)});
 };

  render(){

    const user = { name:"Guest", loggedIn: this.state.globalLoginStatus, globalLogin:this.globalLogin, globalLogout:this.globalLogout}

  return (
   
    <div className="App-wrapper" key="mtgLynx">

    <AuthContext.Provider value={user}>
    <MainApp></MainApp>
    </AuthContext.Provider>
    </div>

  );
  }
}

export default App;

0 个答案:

没有答案