0

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?

Nick
  • 57
  • 1
  • 7

3 Answers3

3
this.setState(prevState => ({ 
  two: { 
    ...prevState.two, 
    number: "300" 
  } 
}));
Taki
  • 17,320
  • 4
  • 26
  • 47
2

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

Diego Bascans
  • 1,083
  • 1
  • 6
  • 14
0

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

How to update nested state properties in React