在redux函数中重构变量

时间:2017-03-08 15:23:48

标签: javascript reactjs variables redux refactoring

我必须重构我的redux函数

在这3个案例中,我以不同的方式重命名变量,我不想要这个

参见示例

case 'INCREMENT_LIKES' :
  const index = action.index;
  return [
    ...state.slice(0,index), // before the one we are updating
    {...state[index], likes: state[index].likes + 1},
    ...state.slice(index + 1), // after the one we are updating
  ]
case 'INCREMENT_COORDINATES' :
  const a = action.index;
  let string = state[a].d || state[a].d2;
  let array = string.split(" ");
  let max = array.length;
  let last = max - 2;
  let i = (state[a].index || 3) + 1;
  if ( i === last ) i = 3;
  if (array[i] !== 'M' && array[i] !== 'L') array[i] = parseInt(array[i]) + 20;
  return [
    ...state.slice(0,a), // before the one we are updating
    {...state[a], d: array.join(' '), index: i, d2: array.join(' '), index: i }, // updating
    ...state.slice(a + 1), // after the one we are updating
  ]
case 'INCREMENT_VIEWBOX' :
  const count = action.index;
  let string2 = state[count].viewBox;
  let array2 = string2.split(" ");
  let max2 = array2.length;
  let i2 = (state[count].index || 2) + 1;
  if ( i2 === max2 ) i2 = 2;
  array2[i2] = parseInt(array2[i2]) - 20;
  return [
    ...state.slice(0,count), // before the one we are updating
    {...state[count], viewBox: array2.join(' '), index: i2},
    ...state.slice(count + 1), // after the one we are updating
  ]
default:
  return state;

这些是3个案例中的不同变量名

const index = action.index;

const a = action.index;

const count = action.index;

相同
let string = state[a].d || state[a].d2;

let string2 = state[count].viewBox;

let array = string.split(" ");

let array2 = string2.split(" ");

如何为所有3个案例重用相同的变量名?

我的意思是对3种不同的情况使用相同的名称,如:

const index - let string - let array

1 个答案:

答案 0 :(得分:5)

您可以通过用大括号括起来为每个案例添加一个范围:

case 'INCREMENT_LIKES' : {
  const index = action.index;
  return [
    ...state.slice(0,index), // before the one we are updating
    {...state[index], likes: state[index].likes + 1},
    ...state.slice(index + 1), // after the one we are updating
  ]
}

case 'SOME_OTHER_ACTION_TYPE' : {
  console.log(index) // -> undefined
}