【问题标题】:Keep getting 'dispatch' undefined with redux-promise使用 redux-promise 继续获得未定义的 'dispatch'
【发布时间】:2017-01-30 06:31:20
【问题描述】:

我对 Redux 及其概念非常陌生,尤其是中间件,所以对于任何愚蠢的错误,我深表歉意。

在我的这个项目中,我需要使用 redux-thunk。我查看了一些关于如何应用它们的指南和解释。然后我一直收到错误“未捕获的类型错误:无法读取未定义的属性'调度'”。我打开了开发者工具并显示了这个错误:

我不知道我是否做对了。以下是我的动作创建者和商店的代码。

actions/index.js

import axios from 'axios';

export function fetchLessons() {
  console.log('called!');
  return function(dispatch) {
    axios.get(`${ROOT_URL}/lessons`)
      .then((response) => {
        dispatch(fetchLessonsSuccess(response))
      })
      .catch((err) => {
        dispatch(fetchLessonsError(err))
      })
  }
}

function fetchLessonsError(){
  return "An error has occured";
}

function fetchLessonsSuccess(response) {
  return {
    type: FETCH_LESSONS,
    payload: request
  };
}

index.js(存储)

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import { Router, browserHistory } from 'react-router';
import rootReducer from './reducers/index';
import routes from './routes';
import promise from 'redux-promise';
import thunk from 'redux-thunk';

const middleware = applyMiddleware(promise(), thunk);
const store = createStore(rootReducer, compose(middleware));

ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory} routes={routes} />
  </Provider>
  , document.querySelector('.container'));

【问题讨论】:

    标签: reactjs redux redux-thunk redux-promise


    【解决方案1】:

    我相信你给applyMiddleware() 的电话有点不对劲。您想直接传递导入的 promise 中间件,而不是调用它:applyMiddleware(promise, thunk)。

    该函数基本上是一个工厂。 Redux 将调用它并传入 store 的 dispatch 函数,然后中间件可以在准备就绪时使用它来调度操作。

    【讨论】:

      【解决方案2】:

      我不完全确定,但像这样

      export function fetchLessons() {
        console.log('called!');
        return function(dispatch) {
          return dispatch({
            type: 'FETCH_LESSONS',
            payload: axios.get(`${ROOT_URL}/lessons`)
              .then((response) => {
                dispatch(fetchLessonsSuccess(response))
              })
              .catch((err) => {
                dispatch(fetchLessonsError(err))
              });
          });
        };
      }
      
      function fetchLessonsError(){
        return "An error has occured";
      }
      
      function fetchLessonsSuccess(response) {
        return {
          type: 'FETCH_LESSONS_FULFILLED',
          payload: response
        };
      }
      

      【讨论】:

        猜你喜欢
        • 2020-10-27
        • 1970-01-01
        • 2018-07-15
        • 2018-08-13
        • 2017-07-18
        • 2018-05-27
        • 2020-10-05
        • 2020-05-17
        • 2019-01-03
        相关资源
        最近更新 更多