Redux动作工厂不支持参数

问题描述 投票:0回答:1

我决定创建减速器和动作工厂,所以我不再重复代码了。减速机工厂工作正常。它是这样的:

const initialState = {
  loading: false,
  error: null,
  data: [],
  entity: null,
  query: null
}

const baseReducer = (name = '') => {  
  return (state = initialState, action) => {
    switch(action.type) {
      case `FETCH_ALL_${name}_BEGIN`:
      case `FETCH_ONE_${name}_BEGIN`:
        return {
          ...state,
          loading: true
        }
      case `FETCH_ALL_${name}_ERROR`:
      case `FETCH_ONE_${name}_ERROR`:
        return {
          ...state,
          loading: false,
          error: action.payload.error
        }
      case `FETCH_ALL_${name}_SUCCESS`:            
        return {
          ...state,
          loading: false,
          data: action.payload.data
        }
      case `FETCH_ONE_${name}_SUCCESS`:
        return {
          ...state,
          loading: false,
          entity: action.payload.data
        }
      default:
        return state;
    }
  }
}

不幸的是,如果我向他们传递任何参数,动作创建者就无法工作。这是我的实现:

import axios from 'axios';

export const actionFactory = (name, action, thunk) => () => {    
  return dispatch => {
    console.log('this one here does not work');
    dispatch({
        type: `${action}_${name}_BEGIN`
      }
    );

    return dispatch(thunk)
      .then(response => {
        dispatch({
          type: `${action}_${name}_SUCCESS`,
          payload: {
            data: response.data
          }
        })
      })
      .catch(error => {
        dispatch({
          type: `${action}_${name}_FAILURE`,
          payload: {
            error: error.message
          }
        })
      });
  }
}

这些是我的两个动作。第一个工作正常,但第二个没有达到动作工厂的实现。我不知道为什么会发生这种情况,但它与传递参数有关。

export const fetchUsers = actionFactory('USERS', 'FETCH_ALL', () => {
    return axios.get('http://localhost:8000/api/user')
  });

export const fetchUser = (body) => actionFactory('USERS', 'FETCH_ONE', () => {
  return axios.get('http://localhost:8000/api/user/' + body);
})

当我在组件中调用它们时,第一个返回所有用户,第二个完全不运行。 Console.log语句不起作用。任何想法我能做些什么呢?我厌倦了重复代码,因为减速机工厂的工作,我现在不想离开它。

javascript reactjs redux redux-thunk reducers
1个回答
1
投票

你正在讨论第二个actionFactory(第二个在调用时返回一个函数)。

所以对于第一个fetchUsers()是好的。

对于第二个,您需要在传递body参数后调用返回的函数。那将是:

fetchUser(主体)()

© www.soinside.com 2019 - 2024. All rights reserved.