创建上下文
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>
)
}
}
App.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,即渲染器中没有消费者标签。