React context does not update

问题: I'm using React 16.6 and my goal is to save user information in context. This is my code: import React, { Component } from 'react'; import ReactDOM from 'react-dom'; i...

问题:

I'm using React 16.6 and my goal is to save user information in context.

This is my code:

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'));

The problem is that the context wont update when the axios returns data and updates the state. state does update but context does not.

This is console log:

{}

{}

{id: 1, personaName: "majid", …}


回答1:

Let's use some trick, don't render anything until response isn't come!!

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>
        )
    }
}
  • 发表于 2018-12-27 07:50
  • 阅读 ( 196 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除