所以这是我目前的减速器:

import { Reducer } from 'redux';
import {
  EventState,
  LOAD_EVENTS,
  LOAD_EVENT_BY_ID,
  FETCH_MORE_EVENTS
} from '../types/eventTypes';

export const initialState = {
  eventsList: [],
  event: undefined,
  isLastPage: false
};

const eventReducers: Reducer<EventState, any> = (
  state = initialState,
  action
) => {
  switch (action.type) {
    case LOAD_EVENTS:
      return {
        ...state,
        eventsList: action.eventsList
      };
    case FETCH_MORE_EVENTS:
      return {
        state,
        eventsList: state.eventsList.concat(action.eventsList),
        isLastPage: action.eventsList.length === 0
      };
    default:
      return state;
  }
};

export default eventReducers;


正如您看到的,LOAD_EVENTSFETCH_MORE_EVENTS都共享键eventsList,在获取更多事件时,我将这样的状态称为state而不是...state,因为它似乎重新初始化了整个reducer的状态。但是,这是正确的方法吗?我认为如果减速器长大,那将是一个错误。

那么我该怎么做才能正确清洁该减速器呢?就像我所需要的那样,先触发LOAD_EVENTS,然后eventsList应该变得清晰,并根据LOAD_EVENTS带来的内容再次填写。基本上,我只需要重置eventsList的状态,但其余部分应保持不变。

最佳答案

当您调用诸如state之类的状态而不是...state时,您无需重新初始化状态,而是将先前的状态存储在新状态中,例如下面的示例:

state = {
  eventsList: [...someEvents],
  event: undefined,
  isLastPage: false,
  state: {
    eventsList: [...someEvents],
    event: undefined,
    isLastPage: false,
    state: {
      eventsList: [...someEvents],
      event: undefined,
      isLastPage: false
    }
  }
};


仅当超级必要时,这不是一个好的模式/做法。

因此,正确的做法是,在获取更多事件时,使用initialState重置了先前的状态。

export const initialState = {
  eventsList: [],
  event: undefined,
  isLastPage: false
};

const eventReducers: Reducer<EventState, any> = (
  state = initialState,
  action
) => {
  switch (action.type) {
    case LOAD_EVENTS:
      return {
        ...state,
        eventsList: action.eventsList
      };
    case FETCH_MORE_EVENTS:
      return {
        ...initialState,
        eventsList: state.eventsList.concat(action.eventsList),
        isLastPage: action.eventsList.length === 0
      };
    default:
      return state;
  }
};


但是怎么说呢,它只需要重置eventsList的状态,但是其余部分应该保持不变,您可以对reducer保持不变:

case LOAD_EVENTS:
  return {
    ...state,
    eventsList: action.eventsList
};


因为像上述示例那样设置eventsList时,将重置eventsList并再次填写新数据。但是,请不要忘记我所说的第一个示例的问题。

10-08 19:34