如何在React-Redux应用程序中加载仅在登录时的用户?

xwbd5t1u  于 2023-06-23  发布在  React
关注(0)|答案(1)|浏览(121)

当我打开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>
  )
}

有没有一种方法可以告诉应用程序只在用户登录时尝试加载?

i34xakig

i34xakig1#

您可以在loadUser中使用提前返回。

export const loadUser = () => async (dispatch, getState) => {
    if (!getState().auth.authenticated) {
        return;
    }

    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
        })
    }
}

相关问题