首页 文章

ReactJS Redux Reduc-thunk无法发送承诺

提问于
浏览
0

当我尝试用redux发送一个承诺时,我有这个消息,我会看到我错了

未捕获错误:操作必须是普通对象 . 使用自定义中间件进行异步操作 .

1)这里是我的createStore

import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import createLogger from 'redux-logger'
import RootReducer from '../reducers/root.reducer'

export default function configureStore(preloadedState) {
  const store = createStore(
      RootReducer,
      preloadedState,
      compose(
          applyMiddleware(thunk), createLogger()
      )
  )
  return store
}

2)在我的组件中,我发送这样的动作

dispatch(myAction(myParam))

3)这是myAction代码

export function myAction(dispatch, myParam){
    return fetchList(myParam)
      .then(response => response.json())
      .then(json => {
        console.log(json)
      })
      .catch(err => {
        if (err)
          throw err
      })
}

但如果我这样称呼我的行动,那就是:

myAction(dispatch, myParam)

我认为存在redux-thunk问题,但为什么......

2 回答

  • 1

    使用 redux-thunk ,您必须从您的动作创建者返回一个功能 . dispatch 将作为第一个参数传递给此函数,因此您可以在函数内的任何位置调用它来执行不同的操作 .

    export function myAction(myParam) {
      return dispatch => {
        fetchList(myParam)
          .then(response => response.json())
          .then(json => {
            dispatch({
              type: FETCH_LIST_SUCCESS,
              list: json
            });
          })
          .catch(err => {
            if (err)
              throw err;
          });
      };
    }
    

    仔细阅读docs .

  • 0

    Thunk允许动作创建者返回一个函数而不是普通对象,所以你就像使用它一样

    export function myAction(myParam) {
      return dispatch => {
        console.log("IN ACTION");
        fetchList(myParam)
        .then(response => response.json())
        .then(json => {
          dispatch({
            type: FETCH_LIST_SUCCESS,
            list: json
          });
        })
        .catch(err => {
          if (err)
          throw err;
        });
      };
    }
    

    你正在返回一个Promise对象,这是问题的一部分 .

相关问题