上下文api状态发生变化,但直到刷新浏览器后才反映出来

时间:2020-07-15 12:31:08

标签: reactjs react-context react-state

我正在更新状态并将令牌存储在本地存储中。 单击登录按钮后,状态会更改,但直到我刷新浏览器选项卡后才会进入仪表板页面。 为什么它不自动检测状态并更新状态?

逻辑:如果令牌在本地存储中可用,则应将其重定向到仪表板。否则,将显示登录页面,并且在身份验证之后应重定向到仪表板。

下面是用户上下文和“登录”页面

UserContext

import React, { createContext, Component } from 'react';
import { Redirect } from 'react-router-dom';

export const UserContext = createContext();
class UserContextProvider extends Component {

    state = {
        isLoading: false,
        isAuthenticated: false,
        token: null,
        UserName: null,
        Email: null,
        Role: null
    }

    auth = (auth, profile) => {
        this.setState = ({
            isAuthenticated: auth,

        }, () => { });
        if (profile) {
            localStorage.setItem("token", profile.token);
            this.setState = ({
                token: profile.token
            }, () => { });
        } else {
            this.setState = ({
                token: null,
                UserName: null,
                Email: null,
                Role: null
            });
        }

    }

    isLoading = load => {
        this.setState({ isLoading: load })
    }

    logout = () => {
        localStorage.removeItem("token")
        this.setState({
            isAuthenticated: false,
            token: null,
            UserName: null,
            Email: null,
            Role: null
        })
    }

    componentDidMount = async () => {
        if (localStorage.getItem("token")) {
            const base64Url = localStorage.getItem("token").split('.')[1];
            const base64 = base64Url.replace('-', '+').replace('_', '/');
            var tokenData = (JSON.parse(window.atob(base64)));
            await this.setState({
                isAuthenticated: true,
                token: localStorage.getItem("token"),
                UserName: tokenData.name,
                Email: tokenData.email,
                Role: tokenData.role

            });
        }
        return <Redirect to="/login" />

    }

    render() {

        return (
            <UserContext.Provider value={{ ...this.state, auth: this.auth, isLoading: this.isLoading, profileData: this.profileData, logout: this.logout }}>
                {this.props.children}
            </UserContext.Provider>
        );
    }
}

export default UserContextProvider;

Login.jsx

const Login = () => {

    const { auth, profileData, token, isAuthenticated } = useContext(UserContext);

    const [email, setemail] = useState('');
    const [password, setpassword] = useState('');
    const [error, setError] = useState(null)

    const handlesubmit = (e) => {
        e.preventDefault();
        const user = {
            Email: email,
            Password: password,
        }
        axios.post("http://localhost:2000/user/", user)
            .then(res => {
                if (res.data.error) {
                    setError(res.data.msg);
                    auth(res.data.valid, null);
                } else if (res.data.valid) {
                    setError(null);
                    auth(res.data.valid, res.data)
                }
            }).catch(error => {
                console.log(error)
            });
    }

    return (
        <div>
            {console.log(isAuthenticated, token)}
            {isAuthenticated ? <Redirect to='/dashboard' /> : <Redirect to='/login' />}
            <div className="container mt-5">
                <div className="col-md-6 mx-auto text-center">
                    <div className="header-title">
                        <h1 className="wv-heading--title">
                            Login Here!
                        </h1>
                    </div>
                </div>
                <div className="row mt-5">
                    <div className="col-4 mx-auto">
                        <div className="myform form ">
                            <form onSubmit={handlesubmit}>

                                <div className="form-group">
                                    <input type="email" name="email" value={email} onChange={(e) => { setemail(e.target.value) }} className="form-control" id="email" placeholder="Email" required />
                                </div>

                                <div className="form-group">
                                    <input type="password" value={password} name="password" onChange={(e) => { setpassword(e.target.value) }} id="password" className="form-control" placeholder="Password" required />
                                </div>

                                {
                                    error ?
                                        <div className="mt-3 mb-3">

                                            <p style={{ color: "red", fontSize: "8" }}> <b>Error :</b> {error}</p>
                                        </div>
                                        :
                                        null
                                }


                                <div className="text-center ">
                                    <button type="submit" className="btn btn-outline-info">Login</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    )
}

export default Login;

1 个答案:

答案 0 :(得分:0)

我明白了。 用户上下文身份验证功能中的setState错误。

相关问题