简体   繁体   English

React Native重置状态的某些属性

[英]React Native reset some property of state

I have a long initial state and I want to reset some of my states onPress of a button. 我有很长的初始状态,我想重置我的一些国家的onPress按钮。

Let's have an example of this.state : 让我们举一个this.state的例子:

this.state = {
  A: "",
  B: 0,
  C: [
    {
      x: 0,
      y: "Palette",
      z: true,
    }
  ],
  tempA: "",
  tempB: 0,
  tempC: [
    {
      x: 0,
      y: "Palette",
      z: true,
    }
  ]
};

And I want to reset those started with temp . 我想重置以temp开头的那些。 So I created: 所以我创建了:

const initialState = {
  tempA: "",
  tempB: 0,
  tempC: [
    {
      x: 0,
      y: "Palette",
      z: true,
    }
  ]
};

but I don't know how can i setState to set this.state.A and reset initialState ! 但是我不知道如何setState设置this.state.A并重置initialState I've tried to use: 我尝试使用:

setState({ A: 10, initialState })
// OR
setState([{ A: 10}, initialState ])

But no result! 但是没有结果!

Any idea? 任何想法?

Thanks in advance! 提前致谢!

Try with object spreading: 尝试传播对象:

setState({ ...initialState, A: 10 })

Also A: 10 should be defined after spreading to let it override the initialState properties. 同样, A: 10应在展开后定义A: 10 ,以使其覆盖initialState属性。

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

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