Reputation: 613
A sample code from an online course:
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),
]
}
}
As the initialState is immutable(always the same), then the state is the same. So, let's say, if I first add an new player, a total of four players now. If then I want to remove the fourth player (whose index is 3 in the array), but how does it work?
case PlayerActionTypes.REMOVE_PLAYER:
return [
...state.slice(0, action.index),
...state.slice(action.index+1),
]
There is no index = 3 in the 'state' (only three players).
I don't understand. Please provide some help on my confusion. Thanks in advance.
Upvotes: 0
Views: 33
Reputation: 15211
export default function Player(state=initialState, action) {
whenever action is dispatched, this function gets called with 2 parameters:
based on those 2, this function returns new app state (which will be used as parameter in next call to this function with new action)
now, for the very first run, when app state is still null, the parameter state
will be set to initialState
. for every next run, since state will no longer be null, your state
parameter will be whatever the current app state is.
check ES6 function default parameters.
Upvotes: 1