当我打开app/website
主页时,我在devtools
中得到错误,比如:
GET http://.../profile 401(未经授权)
这是确定的,因为用户没有登录。
但我想防止这个错误。
下面是一段控制此行为的代码
reducer.js:
export const authReducer = (state = { user: {} }, action) => {
switch (action.type) {
case LOAD_USER_REQ:
return {
loading: true,
isAuthenticated: false
}
case LOAD_USER_SUCCESS:
return {
...state,
loading: false,
isAuthenticated: true,
user: action.payload
}
case LOAD_USER_FAIL:
return {
loading: false,
isAuthenticated: false,
user: null,
error: action.payload
}
case CLEAR_ERRORS:
return {
...state,
error: null
}
default:
return state
}
}
store.js:
...
const store = configureStore({
reducer: {
products: productsReducer,
auth: authReducer,
user: userReducer
}
})
export default store
actions.js:
export const loadUser = () => async dispatch => {
try {
dispatch({ type: LOAD_USER_REQ })
const { data } = await axios.get('/profile')
dispatch({
type: LOAD_USER_SUCCESS,
payload: data.user
})
} catch (error) {
dispatch({
type: LOAD_USER_FAIL,
payload: error.response.data.message
})
}
}
Protected.js:
...
const Protected = () => {
const { isAuthenticated } = useSelector(state => state.auth)
if (!isAuthenticated) {
return <Navigate to='login' />
}
return (
<Outlet />
)
}
export default Protected
App.js:
export default function App() {
...
useEffect(() => {
store.dispatch(loadUser())
}, [])
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="login" element={<Login />} />
<Route element={<Protected />}>
<Route path="profile" element={<Profile />} />
</Route>
</Routes>
</Router>
)
}
有没有一种方法可以告诉应用程序只在用户登录时尝试加载?
1条答案
按热度按时间i34xakig1#
您可以在loadUser中使用提前返回。