---------------秘密页面---------------
我创建了一个简单的MERN应用程序。我使用护照进行身份验证
我有主页,登录、注册秘密和提交页面。只有登录的用户才能看到secret、home和提交页面,只有非登录的用户可以看到登录以及注册页。我使用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_};
谁有更好的主意非常感谢
您是否可以尝试将user_
操作创建者重写为返回函数的函数:
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) {}
};
然后在Secret
组件的useEffect
中,调用user_
操作创建者来创建操作:
useEffect(() => {
dispatch(user_());
}, []);
我不确定这是问题所在,但这似乎确实是应该采取的任何一种方式。