(React/Redux) Redux 操作中的异步问题

无法成功使用过去帖子中的解决方案。


每次useEffect在 app.js 上加载应用程序时,我都尝试运行一个操作,如下所示:


  26 | const App = () => {

  27 |   

  28 |   useEffect(() => {

> 29 |     store.dispatch(loadUser());

  30 |   }, []);

  31 | 

  32 |   return (

我得到的错误:


Error: Actions must be plain objects. Use custom middleware for async actions.

那个行动 :


export const loadUser = () => (dispatch, getState) => {

      dispatch({ type: USER_LOADING})


      const token = getState().auth.token


      const config = {

          headers : {

              "Content-type": "application/json"

          }

      }


      if (token) {

          config.headers["x-auth=token"] = token

      }


      axios.get("/api/auth/user", config) 

      .then(res => dispatch({

          type: USER_LOADED,

          payload: res.data

      }))

      .catch(err => {

          dispatch(returnErrors(err.response.data, err.response.status))

          dispatch({

              type: AUTH_ERROR

          })

      })

  }

我究竟做错了什么?


开心每一天1111
浏览 347回答 3
3回答

茅侃侃

默认情况下,redux 中的操作必须返回一个带有type键的对象。您的 redux 操作创建者正在返回一个函数。这是最常与redux-thunk中间件一起使用的模式。如果redux-thunk需要,中间件允许您的操作返回一个函数,该函数接受多次调用的调度方法。创建 redux 存储时,您需要安装该redux-thunk软件包并将其包含在中间件数组中。

胡子哥哥

Redux 本身就是一个非常简单的工作流程。调度的动作必须是一个对象,通常带有一个类型和一个有效负载。对于需要在操作的各个阶段进行多次分派的异步操作,此工作流程有些痛苦。这就是Redux Thunk或Redux Sagas等其他工具的用武之地。在我看来,您正在使用 Redux Thunk 但尚未连接 Thunk 中间件。无论您在哪里创建商店,都需要像这样应用 redux thunk 中间件。import { createStore, applyMiddleware } from 'redux';import thunk from 'redux-thunk';import rootReducer from './reducers';// Note: this API requires redux@>=3.1.0const store = createStore(rootReducer, applyMiddleware(thunk));

慕村225694

当您在操作中有异步逻辑时,您必须将某种中间件与 redux 集成,即redux-thunk或redux-saga. 我更喜欢 thunk,因为它更易于使用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript