我很難理解 react-router Auth。我已經多次閱讀(可怕的)檔案,并且在網路上遵循了許多教程。沒有一個有效。React 提供的示例是用打字稿撰寫的,這使得它更難理解。請幫我解決這個問題。
他們(React Dev Tutorial)使用背景關系和提供者。但我似乎也無法理解。與 React-router 的其余部分不同,IMO 非常復雜。
當我從 auth.js 運行登錄功能時,它似乎可以作業,然后它只是將鉤子重置為 false 并且永遠不會加載下一頁。我覺得我很接近但是 auth.js 檔案有問題嗎?
應用程式.js
function RequireAuth({children}) {
let location = useLocation();
const { authed } = UseAuth();
console.log(authed);
return authed ? children : <Navigate to="/" state={{from: location}}/>;
}
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<BrowserRouter location={history.location} navigator={history}>
<AuthProvider>
<Routes>
<Route index element={<Login setData={setData} type={type}/>} />
<Route path="adminDashboard" element={
<RequireAuth redirectTo="/">
<AdminDashboard />
</RequireAuth>
}
/>
<Route path="userDashboard" element={
<RequireAuth redirectTo="/">
<UserDashboard />
</RequireAuth>
} />
</Routes>
</AuthProvider>
</BrowserRouter>
</PersistGate>
</Provider>
登錄.js
const auth = UseAuth();
auth.login();
auth.js auth.js 檔案來自一個單獨的教程
import * as React from "react";
const authContext = React.createContext({
authed: false,
login: () => {},
logout: () => {}
});
export default function UseAuth() {
return React.useContext(authContext);
}
export function AuthProvider({ children }) {
const [authed, setAuthed] = React.useState(false);
let auth = UseAuth();
const login = () => setAuthed(true, console.log(authed));
const logout = () => setAuthed(false);
let value = { authed, login, logout };
return (
<authContext.Provider value={value}>
{children}
</authContext.Provider>
);
}
uj5u.com熱心網友回復:
useAuth 回傳 3 個經過身份驗證的東西,login() 和 logout()。所以當你打電話時let auth = useAuth(),auth 是一個包含所有這三個的物件。
嘗試解構到 useAuth 回傳,例如
const { authed, login, logout } = useAuth()
并改用 authed
uj5u.com熱心網友回復:
你似乎很接近。useAuth鉤子回傳一個 object ,但是您在包裝器組件{ authed, login, logout }中命名整個物件并將其用作條件。它是一個已定義的物件,因此它始終是真實的。看起來您只需要從該物件訪問屬性即可知道用戶是否已通過身份驗證。authRequireAuthauthed
function RequireAuth({ children }) {
const location = useLocation();
const { authed } = useAuth();
return auth ? children : <Navigate to="/" state={{from: location}}/>;
}
您似乎也混淆了您的身份驗證背景關系。當useAuth鉤子回傳提供的值時,狀態應該駐留在背景關系提供者中。
const authContext = React.createContext({
authed: false,
login: () => {},
logout: () => {}
});
export default function useAuth() {
return React.useContext(authContext);
}
export function AuthProvider({ children }) {
const [authed, setAuthed] = React.useState(false);
const login = () => setAuthed(true);
const logout = () => setAuthed(false);
return (
<authContext.Provider value={{ authed, login, logout }}>
{children}
</authContext.Provider>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/414882.html
標籤:
