javascript - 在 redux 函数中重构变量

标签 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;

这是三种情况下的不同变量名

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

最佳答案

您可以通过将它们括在大括号中来为每个案例添加一个范围:

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
}

关于javascript - 在 redux 函数中重构变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42675248/

相关文章:

javascript - 取消页面加载时的 FancyBox

reactjs - 无法从 props 初始化状态

javascript - 如何使 Javascript/React/Typescript 提取调用异步?

excel - Stata:从 Excel 导入时以小写重命名变量

python - Flask Python 和 css 变量

javascript - 如何使用 ES6 过滤器和映射将平面结构转换为嵌套结构

javascript - 将 gulp-file 分成几个文件

javascript - jQuery : How to use 2 textboxes to make 1 HTML preview

reactjs - 未捕获的类型错误 : Cannot create property 'empFirstName' on string ''

python - 当作为参数传递给具有可变参数的函数时,列表解包如何工作?