简体   繁体   English

反应还原剂不会变质

[英]react redux reducer not changin

I got this insane problem that I think has more to do about pure JS rather than redux. 我遇到了这个疯狂的问题,我认为有关纯JS而不是redux的更多信息。

My initial state looks like this: 我的初始状态如下:

let data = {
    outputs : ["0", "0", "0", "0"],
    analogIn : "0"
}

and this is part of my reducer so when I try to change a value of the outputs array (eg the 3rd value) 这是我的reducer的一部分,所以当我尝试更改输出数组的值(例如第3个值)

let newstate = Object.assign({}, state);
    switch (action.type) {
        case 'CLICK_OUTPUT':
            let outputs = newstate.outputs
            let status = outputs[action.num]
            let newStatus = (status == "0") ? "1" : "0"
            outputs[action.num] = newStatus
            newstate.outputs = outputs
            console.log(newstate.outputs[action.num])    <-- 1.
            console.log(newstate.outputs)                <-- 2. 
            console.log(newstate)                        <-- 3.
            return newstate
        default:
            return state || data.data
}
  1. Returns "1" which is correct 返回“1”,这是正确的
  2. Returns ["0", "0", "1", "0"] which is correct 返回正确的[“0”,“0”,“1”,“0”]
  3. Returns 返回

    analogIn : "0", outputs : ["0", "0", "0", "0"] analogIn:“0”,输出:[“0”,“0”,“0”,“0”]

so the state is not changed... 所以国家没有改变......

When I try to change the analogIn it works 当我尝试更改模拟时,它可以工作

case 'CHANGE_IN':
    newstate.analogIn = action.val
    return newstate

Any ideas why does this happen? 任何想法为什么会这样? Does it have to do with redux? 它与redux有关吗?

Ok, found the solution. 好的,找到了解决方案。

As it seems using this: 因为它似乎使用这个:

newstate.outputs = outputs

or this: 或这个:

newstate.outputs[num] = "1"

does not work if you want to copy the contents of one array to the value of an object that is an array 如果要将一个数组的内容复制到作为数组的对象的值,则不起作用

The solution was to clone the array 解决方案是克隆数组

newstate.outputs = outputs.slice(0)

I'm not sure if this occured because of es6 or it is pure JS. 我不确定这是因为es6还是纯粹的JS而发生的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM