React redux reducer - 从字符串更改值

时间:2017-09-17 22:10:16

标签: reactjs react-native redux

我试图使用此代码动态更改ma状态值,但它不起作用我在这里做错了。

const defaultState = {
team_a_player_1_points: 0,
team_a_player_2_points: 0,
team_a_player_3_points: 0,
team_a_player_4_points: 0,
team_a_player_5_points: 0,
team_b_player_1_points: 0,
team_b_player_2_points: 0,
team_b_player_3_points: 0,
team_b_player_4_points: 0,
team_b_player_5_points: 0
};

function homepageReducer (state = defaultState , action) {
  switch (action.type) {
    case 'ADD_POINT':
     const scoring_player = `team_${action.player_team}_player_${action.player_number}_points`;
      return {...state, scoring_player: state.scoring_player + 1};
    case 'REMOVE_POINT':
      return {...state, };        
    default:
      return state;
  }
}

1 个答案:

答案 0 :(得分:4)

您正在尝试更新状态中不存在的密钥。 您可以在es6

中使用动态计算的对象键

试试这个

function homepageReducer (state = defaultState , action) {
  switch (action.type) {
    case 'ADD_POINT':
     const scoring_player = `team_${action.player_team}_player_${action.player_number}_points`;
      return {...state, [scoring_player]: state[scoring_player] + 1};
    case 'REMOVE_POINT':
      return {...state, };        
    default:
      return state;
  }
}

请注意,[scoring_player]将在您在州计算之上计算的字符串值中解压缩。

因此,如果您将scoring_player计算为team_a_player_1_points,则下一行的评估结果为:

return {...state, team_a_player_1_points: state['team_a_player_1_points'] + 1};