让我们使用一些技巧,不要渲染任何东西,直到没有回应来!!
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>
)
}
}