当 state = initialState 时,reducer 是如何工作的?

How does reducer works when state = initialState?

来自在线课程的示例代码:

import * as PlayerActionTypes from '../actiontypes/player';

const initialState = [
      {
        name: 'Jim Hoskins',
        score: 31,
      },
      {
        name: 'Andrew Chalkley',
        score: 20,
      },
      {
        name: 'Alena Holligan',
        score: 50,
      },
    ];

export default function Player(state=initialState, action) {
  switch(action.type) {
    case 'PlayerActionTypes.ADD_PLAYER':
      return [
        ...state,
        {
          name: action.name,
          score: 0,
        }
      ];

      case PlayerActionTypes.REMOVE_PLAYER:
        return [
          ...state.slice(0, action.index),
          ...state.slice(action.index+1),
        ]
  }
}

由于initialState是不可变的(总是一样的),那么状态就是一样的。所以,比方说,如果我先添加一个新玩家,现在总共有四个玩家。如果然后我想删除第四个玩家(数组中的索引为 3),但它是如何工作的?

case PlayerActionTypes.REMOVE_PLAYER:
            return [
              ...state.slice(0, action.index),
              ...state.slice(action.index+1),
            ]

'state'中没有index=3(只有三个玩家)。

我不明白。请为我的困惑提供一些帮助。提前致谢。

export default function Player(state=initialState, action) {

无论何时调度操作,都会使用 2 个参数调用此函数:

  1. 状态(即当前应用状态)
  2. 动作

基于这 2 个函数,此函数 returns 新的应用程序状态(将在下次调用此函数时用作新操作的参数)

现在,对于第一个 运行,当应用程序状态仍然为 null 时,参数 state 将设置为 initialState。对于下一个 运行,由于状态将不再为空,因此您的 state 参数将是当前应用程序状态。

检查ES6函数默认参数。