简体   繁体   English

为什么不可变变量会被React的状态机改变?

[英]Why is an immutable variable getting changed by React's state machine?

I have an array const defaultButtons = [{on: false},{on: false},{on: false}] . 我有一个数组const defaultButtons = [{on: false},{on: false},{on: false}] I also have a Component called Keyboard (the keyboard has 3 buttons). 我也有一个称为键盘的组件(键盘有3个按钮)。 I want its state.buttons to default to the defaultButtons array. 我希望它的state.buttons默认为defaultButtons数组。 So I set state.buttons to defaultButtons, but every time I change the state, it also changes the defaultButtons array. 因此,我将state.buttons设置为defaultButtons,但是每次更改状态时,它也会更改defaultButtons数组。 Can I in some way pass the defaultButtons array to React's state machine, without letting it change the original? 我可以以某种方式将defaultButtons数组传递给React的状态机,而不让它更改原始状态机吗?


    const defaultButtons = [{on: false},{on: false},{on: false}];

    class Keyboard extends Component {
      state = {
        buttons: defaultButtons
      }

      componentDidMount(){
        this.setState({buttons: [{on: true},{on: true},{on: true}]}) // changed buttons
        console.log(defaultButtons) // [{on: true},{on: true},{on: true}] ?!?!? WTF
      }

      render(
        return(<div />)
      )

    }

The code you posted is not the code you run yourself, which makes it a bit harder to debug. 您发布的代码不是您自己运行的代码,这使得调试起来有点困难。

this.setState(buttons: [{on: true},{on: true},{on: true}]); // Syntax error

Because fn(buttons: [...]) is not a valid way to write javascript. 因为fn(buttons: [...])不是编写JavaScript的有效方法。 I guess what you are doing in your code, is 我想你在代码中正在做的是

this.setState(buttons = [{on: true},{on: true},{on: true}]);

Which I can understand, because javascript is confusing sometimes. 我能理解,因为javascript有时会造成混淆。 To make the error here clearer, you could rewrite the code as 为了使错误更清晰,您可以将代码重写为

let argument = buttons = [{on: true},{on: true},{on: true}]
this.setState(argument);

Which is functionally exactly the same as the (buttons = [...]) code. 在功能上与(buttons = [...])代码完全相同。

You have to use {} to indicate that what you are sending into setState is an object, like this: 您必须使用{}来指示要发送到setState的对象是一个对象,如下所示:

this.setState({ buttons: [{on: true}, {on: true}, {on: true}] });

You're currently passing a reference to the defaultButtons variable as an initial state. 您当前正在传递对defaultButtons变量的引用作为初始状态。 If you clone the defaultButtons array you won't update the defaultButtons variable when changing the state: 如果克隆defaultButtons数组,则更改状态时不会更新defaultButtons变量:

  state = {
    buttons: [...defaultButtons],
  }

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

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