If the function is not updated

I am new to this amazing site, I just have a problem in my application.

This index.jsI use react-router-domon this page. I just need to show this.state.showfor those who are on the home page. So, in login.js requestI created 'loginToken'code with thissessionStorage.setItem('loginToken', 'Value')

and now I am doing a check for sessionStorage.getItem('loginToken')in index.js

Everything works fine, but my problem occurs when I'm on the home page . This text 'Welcome Back'does not appear automatically. I need to refresh the homepage to see it. I do not know why this is happening.

Is it because I'm using componentWillMount?

I tried to use componentDidMountI had the same problem

import React, {Component} from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import Login from './users/login';
import home from './news/index';

class App extends Component {
    constructor(props){
        super(props);
        this.state = {
            show: false
        }
    }
    componentWillMount(){
        if(sessionStorage.getItem('loginToken')){
            this.setState({show: true});
        }else{
            this.setState({show: false});
        }
    }
    render() {
        return (
            <div>
                {this.state.show?
                <div>welcome back</div>:null
                }
            <Router>
                    <Switch>
                        <Route path="/login" component={Login} />
                        <Route path="/home" component={home} />
                    </Switch>
            </Router>
            </div>
        )
    }
}
export default App;

Thanks for helping me.

+4
1

componentWillMount , , .

, "" , . .

- , , , .

+1

Source: https://habr.com/ru/post/1692945/


All Articles