0

我见过 3 种形式的减速器:

// Form 1
function reducer(state, action) {
  if (state === undefined)
    return state = [];

  // handle action.type
  // ...
}

// Form 2
function reducer(state, action) {
  if (state === undefined)
    state = [];

  // handle action.type
  // ...
}

// Form 3
function reducer(state = [], action) {

  // handle action.type
  // ...
}

它们都一样吗?表格 1 和表格 2 的不同之处在于表格 1 立即返回初始状态,根本不看和照顾action.type

而且我认为Form 2和Form 3完全一样,使用默认参数值。

任何官方文档或规范都可以证实任何声明吗?它认为这意味着,第一次调用减速器时,action.type不会有任何意义。

4

3 回答 3

0

在 Redux reducer 中,如果 state 没有定义,你能立即返回初始状态吗?

我们可以。

但为此,您不需要检查未定义或任何其他非空检查。

switch default 语句会非常顺利地处理它。

function reducer(state, action) {

  switch(action.type){
      //rest case
      default:
      return state;
  }
}

// Form 2
function reducer(state, action) {

    switch(action.type){
        //rest case
      default:
      return state;
    }
}
于 2020-02-12T04:46:41.960 回答
0

你可以简单地使用:redux-starter-kit 中createReducer

微软的这个演示中也使用了它

一个实用函数,允许将 reducer 定义为从动作类型到处理这些动作类型的 case reducer 函数的映射。reducer 的初始状态作为第一个参数传递。

每个 case reducer 的主体都被隐式地封装在对 immer 库中的 producer() 的调用中。这意味着除了返回一个新的状态对象之外,您还可以直接改变传入的状态对象;然后,这些突变将自动有效地翻译成副本,为您提供便利和不变性。

@param initialState — reducer 要返回的初始状态。
@param actionsMap — 从动作类型到特定于动作类型的案例缩减器的映射。

用法

export const LocalStorageReducer = createReducer<Store['localStorage']>(
  new LocalStorage(), // <= where you define the init value of this state
  {
    storeLocalStorageInput(state, action) {
      return state = {...state, [action.payload.item]: action.payload.value};
    },
    clearLocalStorageInput(state, action) {
      return state = new LocalStorage();
    },
  }
);

export const reducer = combineReducers({
  localStorage: LocalStorageReducer,
...

类型createReducer

(alias) createReducer<LocalStorage, CaseReducers<LocalStorage, any>>(initialState: LocalStorage, actionsMap: CaseReducers<LocalStorage, any>): Reducer<LocalStorage, AnyAction>
import createReducer

状态样本

export class LocalStorage {
  /**
   * Editing plan id in planner pages
   */
  planId: string | undefined;
  /***
   * Touched id list
   */
  touchedIdList: Array<string>;
  constructor() {
    this.planId = undefined;
    this.touchedIdList = Array<string>();
  }
}

已经开发出通过库来完成这些事情的方法,在大多数情况下无需手动再次执行。

于 2020-02-12T04:50:18.710 回答
0
  • Redux 初始化它调度一个“虚拟”动作来填充状态。请检查此文档
  • Reducers在任何情况下都不允许返回undefined,必要时可以返回null

从技术上讲,这三个都是相同的,因为减速器第一次使用 dummy 调用,状态不再是 undefined at Form 1。在随后的调用中,它将通过您的应用程序代码中的有意义的操作被调用,并且state = []在那时,它将检查action.type

于 2020-02-12T04:53:34.870 回答