以正确的方式使用redux-thunk和redux-promise-middleware

时间:2017-03-08 22:37:14

标签: javascript reactjs redux redux-thunk redux-promise-middleware

我正在使用react和redux进行一个项目,我已经足够新了,所以我想更好地理解如何将redux-thunk和redux-promise一起使用。 下面你可以看到我的文件,在我的动作中我创建了一个fetch泛型函数apiFetch(),以便每次我需要获取时使用。这个函数返回一个promise,我将在loadBooks()中解析,代码工作并且记录被上传但是当我检查动作的日志时,我看到第一个动作是未定义的,在有BOOKS_LOADING之后, LOAD_BOOKS,BOOKS_LOADING和LOAD_BOOKS_SUCCESS。

我有两个问题:

1)为什么第一个动作未定义且我LOAD_BOOKS而不是LOAD_BOOKS_START?

action @ 22:54:37.403 undefined
core.js:112  prev state Object {activeBook: null, booksListing: Object}
core.js:116  action function (dispatch) {
        var url = './src/data/payload.json';
        dispatch(booksIsLoading(true));
        return dispatch({
          type: 'LOAD_BOOKS',
          payload: new Promise(function (resolve) {
…
core.js:124  next state Object {activeBook: null, booksListing: Object}
action @ 22:54:37.404 BOOKS_LOADING
action @ 22:54:37.413 LOAD_BOOKS
action @ 22:54:39.420 BOOKS_LOADING
action @ 22:54:39.425 LOAD_BOOKS_SUCCESS

2)例如,如果获取的url是错误的,我希望看到操作LOAD_BOOKS_ERROR,而不是这是日志的结果:

action @ 23:06:06.837 undefined action @ 23:06:06.837 BOOKS_LOADING
action @ 23:06:06.846 LOAD_BOOKS GET
http://localhost:8000/src/data/payldoad.json 404 (Not Found) error
apiFetch Error: request failed at index.js:66 error 
TypeError: Cannot read property 'json' of undefined at index.js:90

如果我不使用apiFetch(),但是正常的fetch函数,一切正常,也是错误的一部分,但无论如何LOAD_BOOKS不是LOAD_BOOKS_START。

提前感谢您的帮助!

configureStore.js

import { createStore, applyMiddleware, compose, preloadedState } from 'redux';
import reducers from './configureReducer';
import configureMiddleware from './configureMiddleware';

const middleware = configureMiddleware();
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ||   compose;
const store = createStore(reducers, preloadedState, composeEnhancers(applyMiddleware(...middleware)));
export default store;

动作/ index.js

import fetch from 'isomorphic-fetch';

export const booksIsLoading = (bool) => {
  return {
    type: 'BOOKS_LOADING',
    booksLoading: bool,
  };
};

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

export const apiFetch = (url) => {
  const getPromise = () => (
    fetch(url, {
      method: 'GET',
    })
      .then((response) => {
        if (response.status !== 200) {
          throw Error('request failed');
        }
        return response;
      })
      .catch((err) => {
        console.log('error apiFetch', err);
        // dispatch(fetchBooksError(true));
      })
  );
  return getPromise();
};

export const loadBooks = () => (dispatch) => {
  const url = './src/data/payload.json';
  dispatch(booksIsLoading(true));
  return dispatch({
    type: 'LOAD_BOOKS',
    payload: new Promise((resolve) => {
      delay(2000).then(() => {
        apiFetch(`${url}`)
          // fetch(`${url}`, {
          //   method: 'GET',
          // })
          .then((response) => {
            resolve(response.json());
            dispatch(booksIsLoading(false));
          }).catch((err) => {
            console.log('error', err);
          });
      });
    }),
  });
};

常量/ application.js中

export const LOAD_BOOKS = 'LOAD_BOOKS';

减速器/ reducer_book.js

import initialState from '../model.js';
import * as types from '../constants/application';

export default function (state = initialState, action) {
  switch (action.type) {
    case `${types.LOAD_BOOKS}_SUCCESS`: {
      console.log('reducer', action.payload);
      const data = action.payload.data.items;
      const items = Object.values(data);

      if (items.length > 0) {
        return {
          ...state,
          books: Object.values(data),
          booksFetched: true,
          booksError: false,
        };
      }

      return state;
    }

    case `${types.LOAD_BOOKS}_ERROR`: {
      return {
        ...state,
        booksError: true,
      };
    }

    case 'BOOKS_LOADING':
      return {
        ...state,
        booksLoading: action.booksLoading,
      };

    default:
      return state;
  }
}

1 个答案:

答案 0 :(得分:1)

您指定了中间件的顺序?

以下用法使操作变为未定义:

' applyMiddleware(reduxPromiseMiddleware(),reduxThunk)'

请将订单更改为:(首先是thunk!)

' applyMiddleware(reduxThunk,reduxPromiseMiddleware())'