简体   繁体   English

反应上下文 API 身份验证不起作用

[英]React context API authentication not working

I'm trying to set up a simple authentication system using react's context api.我正在尝试使用 react 的上下文 api 设置一个简单的身份验证系统。 I have two react pages here using react router, Login.js and App.js.我在这里有两个使用反应路由器的反应页面,Login.js 和 App.js。

Here's App.js, I want it to use the isAuthenticated boolean from the context api to decide which page to render:这是 App.js,我希望它使用上下文 api 中的 isAuthenticated 布尔值来决定要呈现哪个页面:

App.js:应用程序.js:

 function App() { const { isAuthenticated } = useContext(AuthContext); return ( <div className="App"> <AuthContextProvider> <Router> <Routes> <Route path="/" element={isAuthenticated ? <Home /> : <Login />} /> <Route path="/register" element={isAuthenticated ? <Home /> : <Register />} /> </Routes> </Router> </AuthContextProvider> </div> ); }

Here's how login.js authenticates the user:以下是 login.js 对用户进行身份验证的方式:

 const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const { dispatch } = useContext(AuthContext); const handleClick = (e) => { e.preventDefault(); dispatch({ type: "LOGIN_START" }); try { const credentials = { email: email, password: password, } //Make login request to the server, and use the userID it sends back to authenticate the user //Currently has a bug where userID is blank on first call, but works on later calls axios.post('/auth/login', credentials) .then(response => { dispatch({ type: "LOGIN_SUCCESS", payload: response.data }); // console.log(userID); // console.log(isAuthenticated); }) .catch(err => { console.log(err) dispatch({ type: "LOGIN_FAILURE", payload: err }); }); } catch(err) { console.log(err); } }

Now there are 2 issues here:现在这里有2个问题:

  1. In login.js, when I click the login button that calls handleClick, and I do console.log(isAuthenticated), it logs false the first time.在 login.js 中,当我单击调用 handleClick 的登录按钮并执行 console.log(isAuthenticated) 时,它第一次记录为 false。 Any time after that it will log true.之后的任何时候它都会记录为真。
  2. In App.js, isAuthenticated never changes to true, even while login.js will console.log it as true, so the user is never brought to the home page.在 App.js 中,isAuthenticated 永远不会更改为 true,即使 login.js 会将其 console.log 为 true,因此用户永远不会被带到主页。

I've been struggling with this for a while now, and I just can't figure out what's going wrong here.我已经为此苦苦挣扎了一段时间,我只是无法弄清楚这里出了什么问题。 I think it may have something to do with App.js not rerendering after the user logs in but I'm not sure.我认为这可能与 App.js 在用户登录后没有重新渲染有关,但我不确定。

I also have three files handling the authorization context.我还有三个文件处理授权上下文。 I don't think these are causing the issue but I will provide the code just in case I'm missing something我不认为这些是导致问题的原因,但我会提供代码以防万一我遗漏了什么

AuthContext.js: AuthContext.js:

 import { createContext, useReducer } from "react"; import AuthReducer from "./AuthReducer"; const initialState = { userID: null, isAuthenticated: false, error: false, } export const AuthContext = createContext(initialState); export const AuthContextProvider = ({ children }) => { const [state, dispatch] = useReducer(AuthReducer, initialState); return ( <AuthContext.Provider value={{ userID: state.userID, isAuthenticated: state.isAuthenticated, error: state.error, dispatch, }}> {children} </AuthContext.Provider> ) }

AuthActions.js: AuthActions.js:

 export const LoginStart = (userCredentials) => ({ type: "LOGIN_START", }); export const LoginSuccess = (userID) => ({ type: "LOGIN_SUCCESS", payload: userID, isAuthenticated: true, }); export const LoginFailure = (error) => ({ type: "LOGIN_FAILURE", payload: error, isAuthenticated: false, });

AuthReducer.js: AuthReducer.js:

 const AuthReducer = (state, action) => { switch(action.type) { case "LOGIN_START": return { userID: null, isAuthenticated: false, error: false, } case "LOGIN_SUCCESS": return { userID: action.payload, isAuthenticated: true, error: false, } case "LOGIN_FAILURE": return { userID: null, isAuthenticated: false, error: action.payload, } default: return state; } } export default AuthReducer;

Any help is appreciated, thanks!任何帮助表示赞赏,谢谢!

我想通了,我只需将 AuthContext Provider 从 App.js 移到 index.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM