【发布时间】:2021-08-16 21:42:43
【问题描述】:
我创建了简单的 MERN 应用。我使用护照进行身份验证。
我有 home、login、register secret 和 submit 页面有.只有登录的用户可以看到 secret 、 home 和 submit 页面,只有未登录的用户可以看到 login 和 注册页面。我使用 axios 后端发送数据。用户登录,注册成功,但登录后用户多次获取用户数据。我不知道如何解决这个问题。我的后端没有错误。它运作良好。
-------------- 秘密页面--------------
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Redirect } from "react-router";
import { user_ } from "../actions/register_action";
const Secret = ()=>{
const dispatch = useDispatch();
const user = useSelector( state => state.user );
useEffect( ()=>{
dispatch( user_ );
},[] );
console.log(user);
if(user === null) return <Redirect to = "/login" />
else
return (
<div className="jumbotron text-center">
<div className="container">
<i className="fas fa-key fa-6x"></i>
<h1 className="display-3">You've Discovered My Secret!</h1>
<p className="secret-text">Jack Bauer is my hero.</p>
<hr />
<a className="btn btn-light btn-lg" href="/logout" role="button">Log Out</a>
<a className="btn btn-dark btn-lg" href="/submit" role="button">Submit a Secret</a>
</div>
</div>
);
}
export default Secret;
------------- 动作 --------------
import { fail, user, USER_LOGIN_FAIL, USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS,
USER_REGISTER_FAIL, USER_REGISTER_REQUEST, USER_REGISTER_SUCCESS
} from "../constants/all";
import axios from "axios";
const user_Register = (email, password) => async (dispatch) =>{
dispatch({ type: USER_REGISTER_REQUEST });
try {
const {data} = await axios( {
method: "POST",
data: {
"username": email,
"password": password
},
withCredentials: true,
url: "http://localhost:3001/register"
});
dispatch({ type: USER_REGISTER_SUCCESS, payload: data });
} catch (error) {
dispatch({type: USER_REGISTER_FAIL, error: error.message});
}
}
const user_Login = (email, password) => async (dispatch) =>{
dispatch({ type: USER_LOGIN_REQUEST });
try {
const {data} = await axios( {
method: "POST",
data: {
username: email,
password: password
},
withCredentials: true,
url: "http://localhost:3001/login"
});
dispatch({ type: USER_LOGIN_SUCCESS, payload: data });
} catch (error) {
dispatch({type: USER_LOGIN_FAIL, error: error.message});
}
}
const user_ = async (dispatch) => {
try{
const {data} = await axios({
method: "GET",
withCredentials: true,
url: 'http://localhost:3001'
});
if(data.isAuth){
dispatch({type:user, payload:data});
}
else{
dispatch({type: fail});
}
}
catch (error){
}
}
export {user_Register, user_Login, user_};
谁有更好的主意? 非常感谢!
【问题讨论】:
标签: reactjs redux react-redux axios redux-thunk