继续发送'发送'未定义的redux-promise

时间:2016-09-21 20:38:34

标签: reactjs redux redux-thunk redux-promise

我是Redux及其概念的新手,特别是中间件,所以我为任何愚蠢的错误道歉。

在我的这个项目中,我需要使用redux-thunk。我已经查看了一些关于如何应用它们的指南和解释。然后我一直收到一个错误" Uncaught TypeError:无法读取属性' dispatch'未定义"。我打开了开发人员工具并显示了这个错误:

enter image description here

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

动作/ 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'));

2 个答案:

答案 0 :(得分:4)

我相信您对applyMiddleware()的电话略有偏差。您希望直接传递导入的promise中间件,而不是调用它:applyMiddleware(promise, thunk)

该功能基本上是一个工厂。 Redux将调用它并传入商店的dispatch功能,中间件随后可以使用该功能在其准备就绪时发送操作。

答案 1 :(得分:0)

我不完全确定,但这样的事情

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
  };
}