首页 > 解决方案 > 如何使用 ReactJS 组件添加用户身份验证

问题描述

我想实现基于 ReactJS 组件的用户身份验证。我是 ReactJS 的新手,它是一个团队软件项目,所以我们不使用 webhook,而是使用组件。身份验证本身正在工作,但不是内容之后的呈现。

在 app.js 文件中,我使用条件渲染来显示内容或登录页面:

if (this.getToken('token') === null || this.getToken('token') === undefined) {

  shownComponent = <LoginComponent token={this.state.token} setToken={this.setToken} />;
} else {
  shownComponent = <MainComponent />;
}

在 LoginComponent 中,我实现了以下逻辑:

registerUser = () => {
    const data = {
        userName: this.state.userName,
        userPassword: this.state.userPassword
    }
    return fetch('/users/createUser', {
        method: 'post',
        mode: 'cors',
        headers:{
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Accept': 'application/json'
        },
        body: JSON.stringify(data),
    })
        .then((data) => {
            if(data.status === 200){
                console.log('User has been stored to database');
                return true
            }
        })
        .catch((error) => console.log( error.response.request) );
}

loginUser = () => {
    return fetch('/login',{ headers:{
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Accept': 'application/json'
        } })
        .then((response) =>{
            return response.json();
        })
        .then((data) =>{
            return data;
        });

}

login = async () => {

    this.setState({loggedin: true})
    const registered = await this.registerUser()
    const userToken = await this.loginUser();
    this.props.setToken(userToken)

}

从登录表单调用登录功能后(不是复制粘贴在这里),它只会重新呈现登录页面,但不会重定向回 app.js 并现在呈现主要内容。

标签: reactjsauthenticationcomponentsrender

解决方案


推荐阅读