错误:操作必须是普通对象.在 redux 中使用自定义中间件进行异步操作 [英] Error: Actions must be plain objects. Use custom middleware for async actions in redux

查看:56
本文介绍了错误:操作必须是普通对象.在 redux 中使用自定义中间件进行异步操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的动作创建者的代码:

Below is the code for my action creator:

export function fetchPosts()
  {
    const request = axios.get(`${ROOT_URL}/posts${API_KEY}`);
    return
      {
        type: FETCH_POSTS;
        payload: request

      };
  }

接下来键入:FETCH_POSTS,如果我添加 , 而不是 ;我收到错误意外令牌.这是动作创建者的语法吗?

Next to type: FETCH_POSTS, if i add , instead of ; i get the error Unexpected token. Is that the syntax for action creators?

然后如果我用 ;编译时出现错误操作必须是纯 Javascript 对象.

Then if i replace , with ; upon compile i get the error 'Actions must be plain Javascript Objects.

知道为什么吗?

推荐答案

GibboK 的回答已经指出了语法错误.

GibboK's answer has already pointed out the syntax error.

但是,我认为您没有理解正确使用动作.你跑:

However, I don't think you understand using actions properly. You run:

const request = axios.get(`${ROOT_URL}/posts${API_KEY}`);

这是在创建一个承诺.您当前正在操作中返回此内容.Reducer 是确定性的 &没有副作用,因此为什么动作应该是普通的 JS 对象.您不应该提交承诺.

This is creating a promise. You are currently returning this in an action. Reducers are meant to be deterministic & side effect free, hence why actions should be plain JS objects. You should not be submitting a promise.

相反,您应该使用一些相关的中间件,例如redux-thunkredux-saga 或其他东西.您应该在实际承诺解决后发送操作.

Instead, you should be using some relevant middleware, e.g. redux-thunk, redux-saga or something else. You should send an action when the actual promise has resolved.

作为一个简单的人为例子,使用redux-thunk:

As a simple contrived example, using redux-thunk:

export const fetchPosts = () => (dispatch) => {
    // Send action to notify request started. Reducers often want to
    // update the state to record that a request is pending, e.g. for
    // UI purposes.
    dispatch({type: FETCH_POSTS_START});

    // Start request
    request = axios.get(`${ROOT_URL}/posts${API_KEY}`)
       .then(res => { 
          // Successfully received posts, submit response data
          dispatch({type: FETCH_POSTS_COMPLETE, payload: res.data})
        })
       .catch(err => { 
          // API call failed, submit error
          dispatch({type: FETCH_POSTS_ERROR, payload: err})
        });
};

请注意,此代码只是一个示例,不一定适合在生产系统中使用.

这篇关于错误:操作必须是普通对象.在 redux 中使用自定义中间件进行异步操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆