首页 > 解决方案 > Redux-Thunk:动作必须是普通对象。使用自定义中间件进行异步操作

问题描述

无法解决这个问题,使用 react-native 和 redux-thunk。

我正在尝试将数据发布到 firebase.io 并反复收到相同的错误:操作必须是普通对象。使用自定义中间件进行异步操作。

减速器/index.js

import { createStore, combineReducers, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk'
import PlacesReducer from './placesReducer'


const rootReducer = combineReducers({
  places : PlacesReducer,
    });

let composeEnhancers = compose;

if (__DEV__) {
    composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
}

const configureStore = () => {
    return createStore(rootReducer, applyMiddleware(thunk));
};

export default configureStore;

动作/index.js

export const addPlace = (placeName, location, image) => {
    return dispatch => {
        const placeData = {
            name: placeName,
            location: location
        };
        fetch("https://awesome-places-b592c.firebaseio.com/placesReducer.json", {
            method: "POST",
            body: JSON.stringify(placeData)
        })
        .catch(err => console.log(err))
        .then(res => res.json())
        .then(parsedRes => {
            console.log(parsedRes);
        });
    };
};

减速器/placesReducer.js

const initialState = {
  places: []
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "ADD_PLACE":
      return {
        ...state,
        places: state.places.concat({
          key: Math.random(),
          name: action.placeName,
          image: {
            uri: action.image.uri,
            location: action.location
          }
        })
      };
    default:
      return state;
  }
};

export default reducer;

感谢所有帮助,谢谢。


更新

createStore()在 reducers/index.js中为函数添加了 initialState 参数

const configureStore = () => {
  return createStore(rootReducer, {places: []}, applyMiddleware(thunk));
};

仍然收到相同的错误

标签: androidreact-nativereduxredux-thunk

解决方案


您需要dispatch在异步请求完成后执行这些操作

.then(parsedRes => {
     console.log(parsedRes);
     dispatch({
       type: YOUR_REDUCER_TYPE,
       parsedRes
    })
});

同样如createStore 文档中所述,您需要添加initialState

(reducer, preloadedState, enhancer)

推荐阅读