使用redux-thunk时,动作可能没有未定义的“ type”属性错误

时间:2018-12-07 21:28:50

标签: react-native react-redux redux-thunk

我正在尝试测试redux-thunk进行异步调用,我创建了3个动作(请求,成功,失败),并创建了thunk方法来相应地返回调度的动作。

textDirection

在我的组件中,我import { createReducer, createActions } from "reduxsauce"; import Immutable from "seamless-immutable"; import api from "../Services/FixtureApi"; export const INITIAL_STATE = Immutable({ Data1: [], loadingData: false, error: null }); const { Types, Creators } = createActions({ requestData1: null, receiveData1: null, failedData1: null }); export const ExampleTypes = Types; export default Creators; export function getData() { return dispatch => { dispatch(requestData1()); var promise = new Promise((resolve, reject) => { const param1 = ""; setTimeout(() => { resolve(api.getData(param1)); }, 2000); }); return promise .then(res => { dispatch(receiveData1(res.data)); }) .catch(err => { dispatch(failedData1(err.message)); }); }; } export const requestData1 = state => ({ ...state, loadingData: true }); export const receiveData1 = (state, action) => ({ ...state, Data1: [...state.Data1, ...action.payload], loadingData: false }); export const failedData1 = (state, action) => ({ ...state, loadingData: false, error: action.payload }); export const reducer = createReducer(INITIAL_STATE, { [Types.REQUEST_DATA1]: requestData1, [Types.RECEIVE_DATA1]: receiveData1, [Types.FAILED_DATA1]: failedData1 }); 这样的connect动作

getData

运行此命令会导致以下错误

enter image description here

2 个答案:

答案 0 :(得分:0)

您需要一个ActionTypes.js文件,该文件声明所有操作类型。例如,

export const ADD_FAVORITE = 'ADD_FAVORITE';

然后在ActionCreators.js文件中,引用ActionType。

import * as ActionTypes from './ActionTypes';

export const postFavorite = (dishId)  => (dispatch) => {
     dispatch(addFavorite(dishId));    
};
export const addFavorite = (dishId) => ({
    type: ActionTypes.ADD_FAVORITE,
    payload: dishId
});

在我的组件中,我将在按钮onPress事件上调用postFavorite。希望这个例子有帮助。

答案 1 :(得分:0)

我应该从reduxsauce返回的动作创建者对象中分派动作。所以正确的电话应该是这样

export function getData() {
  return async dispatch => {
    dispatch(Creators.requestData1());
    var promise = new Promise((resolve, reject) => {
      const param1 = "";
      setTimeout(() => {
        resolve(api.getData(param1));
      }, 2000);
    });

    try {
      const res = await promise;
      if (!res.ok) throw new Error(res.error);
      dispatch(Creators.receiveData1(res.data));
    } catch (err) {
      dispatch(Creators.failedData1(err.message));
    }
  };
}