我正在使用React 16.6,我的目标是在上下文中保存用户信息。
这是我的代码:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from "react-router-dom";
import Axios from 'axios';
import './assets/css/bootstrap.min.css';
import './assets/css/main.css';
import Default from './default';
import Login from './login';
import PrivateRoute from './private-route';
import UserInfo from './user-info';
class App extends Component {
constructor(props) {
super(props)
this.state = {
user: {}
}
}
componentDidMount = () => {
const token = localStorage.getItem('token');
if (token) {
Axios.get('/getuser', {
headers: {
"Authorization": "Bearer " + token
}
}).then(res => {
if (res.data) {
this.setState({ user: res.data });
}
}).catch(err => {
console.log('err login: ', err);
localStorage.clear();
// delete storage
});
}
}
render() {
console.log(this.state.user);
return (
<Router>
<div>
<UserInfo.Provider value={this.state.user}>
<Route exact path="/login/:token" component={Login} />
<Route exact path="/" component={Default} />
<PrivateRoute exact path="/protected" component={() => <div>Protected</div>} />
</UserInfo.Provider>
</div>
</Router>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
问题是当axios返回数据并更新状态时,上下文不会更新。状态会更新,但上下文不会更新。
这是控制台日志:
{}
{}
{id:1,personaName:“ majid”,...}
答案 0 :(得分:0)
让我们使用一些技巧,在响应不来之前不要渲染任何东西!
class App extends Component {
constructor(props) {
super(props)
this.state = {
user: {},
mounted: false
}
}
componentDidMount = () => {
const token = localStorage.getItem('token');
if (token) {
Axios.get('/getuser', {
headers: {
"Authorization": "Bearer " + token
}
}).then(res => {
if (res.data) {
this.setState({ user: res.data, mounted: true });
}
}).catch(err => {
console.log('err login: ', err);
localStorage.clear();
// delete storage
});
}
}
render() {
if (!this.state.mounted) {
return <div>Loading...</div>
}
return (
<Router>
<div>
<UserInfo.Provider value={this.state.user}>
<Route exact path="/login/:token" component={Login} />
<Route exact path="/" component={Default} />
<PrivateRoute exact path="/protected" component={() => <div>Protected</div>} />
</UserInfo.Provider>
</div>
</Router>
)
}
}