创建上下文
export default React.createContext({
user:null,
login:()=>{}
})
上下文控制器
export default class ContextHandler extends Component{
state = {
user: null,
}
logout = () => {
this.setState({
user: null
})
}
login = user => {
this.setState({
user: user
})
};
render(){
return(
<AuthContext.Provider value={{ user: this.state, login: this.login, logout: this.logout }} >
{this.props.children}
</AuthContext.Provider>
)
}
}
应用程序.js
class App extends Component{
render() {
return (
<BrowserRouter>
<div>
<Switch>
<Route path="/" exact component={Header} />
<Route path="/login" exact component={Login} />
<Route path="/profile" exact component={UserProfile} />
<Route path="/inputform" exact component={InputForm} />
</Switch>
</div>
</BrowserRouter>
)
}
}
export default App;
index.js
ReactDOM.render((
<ContextHandler>
<App/>
</ContextHandler>
),
document.getElementById('root'));
registerServiceWorker();
用户个人资料页面
componentDidMount() {
if (!this.context.user) {
return ( <Redirect to = "/login"/> )
}
else{
this.setState({
loading:true
})
getUserEntries(this.context.user.token,(entries)=>{
if(entries !== null){
this.setState({
userEntries:entries
})
}
})
}
}
render() {
let samples, producers
if(!this.context.user){
return(
<Redirect to="/login"/>
)
}
if (this.state.userEntries) {
samples = (this.buildList(this.state.userEntries.samples))
producers = (this.buildList(this.state.userEntries.producers))
}
登录后,我将被定向到具有正确上下文的用户页面。一旦我导航到另一个页面并尝试返回用户个人资料页面,上下文就会丢失。我必须重新登录??
唯一使用上下文的两个组件是导航栏和用户配置文件页面。注意:我使用的是新的 16.6 上下文 API,即渲染中没有消费者标签。