简体   繁体   中英

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.

Let's have an example of 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 . 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 ! 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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