简体   繁体   中英

How to change state in ReactJS?

I am trying to change the state, but it is not working.

This is my state in App.js:

class App extends React.Component {    
state = {
    one: [
      {
    id: 1,
    sum: "400",
      }
    ],
    two: {
      title: "test",
      number: "0",
    }
  };

And here is my function:

Change = (value) => {
    this.setState({ number: "300" });

But the number does not change. I have also tried:

Change = (value) => {
    this.setState({ two.number: "300" });

But this is not working either. Can someone help me?

this.setState(prevState => ({ 
  two: { 
    ...prevState.two, 
    number: "300" 
  } 
}));

You can try something like this.

var two = { ...this.state.two }
two.number = "300";
this.setState({two})

Craete a dummy object to handle your state object, and then you set it into the state using the setState

You are not properly accessing the nested property. This has been answered here

How to update nested state properties in React

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