ReactJS + Redux + Redux-thunk无法发送承诺

问题描述 投票:1回答:2

当我尝试用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问题,但为什么......

reactjs redux jsx redux-thunk
2个回答
2
投票

使用redux-thunk,您必须从您的动作创建者返回一个功能。 dispatch将作为第一个参数传递给此函数,因此您可以在函数内的任何位置调用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对象,这是问题的一部分。

© www.soinside.com 2019 - 2024. All rights reserved.