Javascript 在redux函数中重构变量
我必须重构我的redux函数 在这3种情况下,我以不同的方式重命名变量,我不希望这样 参见示例Javascript 在redux函数中重构变量,javascript,reactjs,variables,redux,refactoring,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(
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;
及
如何在所有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
}
您可以通过将每个案例用花括号括起来为其添加范围:
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
}