简体   繁体   English

如何在ReactJS中更改状态?

[英]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: 这是我在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 创建一个虚拟对象来处理您的状态对象,然后使用setState将其设置为状态

You are not properly accessing the nested property. 您没有正确访问嵌套属性。 This has been answered here 这已经在这里回答了

How to update nested state properties in React 如何在React中更新嵌套状态属性

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

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