gpt4 book ai didi

javascript - 在 redux 函数中重构变量

转载 作者:行者123 更新时间:2023-11-30 08:27:44 24 4
gpt4 key购买 nike

我必须重构我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com