首页 > 解决方案 > 使用 redux 和 redux thunk 反应原生多动作

问题描述

我是反应新手,并试图为异步 api 调用实现 redux/redux-thunk。我有 5 个部分,想调用 5 个不同的 Api。我的问题是在 props 状态下我只能得到一个最后执行的 api 数据,我需要创建多个 reducer 还是需要将数据合并到一个对象中?

const mapStateToProps = (state) => ({
    isLoading: state.serviceReducer.isLoading,
    error: state.serviceReducer.error,
    data: state.serviceReducer.data,
    UserMaster: state.UserMasterReducer
  });
function mapDispatchToProps(dispatch) {
    return {
        updateUserMaster: (data) => dispatch({ type: 'UPDATE_USER_MASTER', payload: data }),
        ApiService1:  (url,payload,id) => dispatch(ApiService(url,payload,id)),
        ApiService2:  (url,payload,id) => dispatch(ApiService(url,payload,id)),
    }
}

减速器。

import * as Actions from '../action/ActionTypes'

const ServiceReducer = (state = { isLoading: false, error: undefined, data: {}, ActionId: undefined }, action) => {
    switch (action.type) {
        case Actions.SERVICE_PENDING:
            return Object.assign({}, state, {
                isLoading: true,
                ActionId:action.id
            });
        case Actions.SERVICE_ERROR:
            return Object.assign({}, state, {
                isLoading: false,
                error: action.error,
                ActionId:action.id
            });
        case Actions.SERVICE_SUCCESS:
            return Object.assign({}, state, {
                isLoading: false,
                data: action.data,
                ActionId:action.id
            }); 
        default:
            return state;
    }
}

export default ServiceReducer;

行动

export const serviceActionPending = (id) => ({
    type: ActionTypes.SERVICE_PENDING,
    id:id
})

export const serviceActionError = (error,id) => ({
    type: ActionTypes.SERVICE_ERROR,
    error: error,
    id:id
})

export const serviceActionSuccess = (data,id) => ({
    type: ActionTypes.SERVICE_SUCCESS,
    data: data,
    id:id
})

标签: react-nativeredux

解决方案


推荐阅读