如何使用 React/Redux 获取登录用户的用户名(或任何其他数据)

Tes*_*uji 5 javascript reactjs redux

存储用户登录数据(主要是用户名或 uuid)的最佳且安全的方法是什么。那么,我可以在其他组件中使用它吗?我想了几种方法来做到这一点。

  1. 登录/注册时,将用户名存储在本地存储中,并在身份验证结束时将其删除。(非常容易实现,但很可能是最不安全的)
  2. 通过 AuthLogin/AuthSignup 方法传递电子邮件,但我似乎不知道如何通过路由器传递电子邮件。我还注意到,如果浏览器刷新,即使用户仍然登录,这也不起作用。
  3. Cookies(还不知道如何在 React 中使用它们)。

我的 authLogin 方法:


export const authLogin = (email, password) => {
    return dispatch =>{
        dispatch(authStart());
        axios.post('http://127.0.0.1:8000/rest-auth/login/',{
            email: email,
            password: password,

        })
        .then(res => {
            const token = res.data.key;
            const expirationDate = new Date(new Date().getTime() + 3600 * 1000);
            localStorage.setItem('token',token);
            localStorage.setItem('expirationDate',expirationDate)
            localStorage.setItem('email', email)#method 1
            console.log("My token",localStorage.getItem('token'))
            dispatch(authSuccess(token,email));#method 2
            dispatch(checkAuthTimeout(3600));
        })
        .catch(err => {
            dispatch(authFail(err))
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

Tre*_*son 0

我认为你的想法是正确的。像您正在做的那样对用户进行身份验证,将令牌存储在 localStorage 中,并将用户数据保存在 redux 中。由于刷新会导致 redux 存储重新启动,并且您仍然需要用户数据,因此我会在应用程序中的某个位置分派一个操作,可能是在应用程序首次安装时在应用程序的根目录周围,以根据保存的令牌获取登录的用户数据在本地存储中。

像这样的东西:

class App extends Component {

    componentDidMount() {
        // User will come from the store. If we do not have a user,
        // but we have a token, then the user is logged in
        if (!this.props.user && sessionStorage.getItem('token')) {
          // a redux dispatch function to authenticate a JWT
          this.props.validateJWT();
        }
    }
}

Run Code Online (Sandbox Code Playgroud)

至于通过路由器传递道具,您必须使用 renderProp,这可能有点棘手。您能分享一下您的路由器问题的代码吗?