我正在处理一些 svg 元素,我已经构建了一个增量按钮。
增量按钮采用 path d
值将其转换为数组并从数组的第三个元素求和 5
。如果元素是 'L'
或 'M'
它什么都不做
这里是 redux 中的点击函数,它采用递增 Action 状态的值
const a = action.index;
let string = state[a].d;
它转换成一个数组
let array = string.split(" ");
然后它完成我在循环中所说的所有计算
查看完整的 redux 函数
switch(action.type) {
case 'INCREMENT_COORDINATES' :
console.log("incrementing coordinaates")
const a = action.index;
let string = state[a].d;
let array = string.split(" ");
let max = array.length;
let i = 3;
let click = () => {
i++;
if ( i === max ) i = 3;
if (array[i] !== 'M' && array[i] !== 'L') array[i] = parseInt(array[i]) + 5;
array.join(' ');
};
return [
...state.slice(0,a), // before the one we are updating
{...state[a], d: click()}, // updating the with the click function
...state.slice(a + 1), // after the one we are updating
]
default:
return state;
}
边调试边看视频演示http://www.fastswf.com/uSBU68E
如您所见,代码进行了正确的计算,它将第四个元素的 5
相加,并返回数字 331
。一切都很好!但问题是我需要将它作为 '331'
返回,这是数组的一个新元素以继续循环。
我已经使用相同的代码构建了一个演示,它可以完美地工作并实现我想要实现的目标!所以当我在我的 redux 函数中应用它时,我不明白我做错了什么。
参见 jsBin完美如我所愿。
最佳答案
已编辑:
您的
click
函数不返回任何值,因此array.join(' ')
结果未分配到任何地方,属性d
保持未分配状态。let click = () => { i++; if ( i === max ) i = 3; if (array[i] !== 'M' && array[i] !== 'L') array[i] = parseInt(array[i]) + 5; return array.join(' '); };
每次调用 increment_coordinates 操作时,都会执行
case 'INCREMENT_COORDINATES' :
之后 block 中的整个代码。在这种情况下,重要的是变量i
在每次调用时都是一个新变量,初始化为 3。在执行click
函数期间,i
增加到4 然后它超出了它的范围,所以它的值(value)就丢失了。
我的建议是在state
中包含当前索引(希望这会起作用并且我已经删除了click
函数,因为它会重新创建每个调用并且只调用一次)
请记住在您第一次将坐标传递给 reducer 的行中也包含索引,或者检查state[a]
是否包含属性index
并设置i= 3
如果没有。switch(action.type) { case 'INCREMENT_COORDINATES' : console.log("incrementing coordinaates") const a = action.index; let string = state[a].d; let array = string.split(" "); let max = array.length; let i = (state[a].index || 3) + 1; if ( i === max ) i = 3; if (array[i] !== 'M' && array[i] !== 'L') array[i] = parseInt(array[i]) + 5; return [ ...state.slice(0,a), // before the one we are updating {...state[a], d: array.join(' '); index: i}, // updating ...state.slice(a + 1), // after the one we are updating ] default: return state; }
关于javascript - 在数组中递增单击 Redux 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42179256/