简体   繁体   English

this.setState 不更新初始空 state 数组

[英]this.setState not updating initial empty state array

Initially I have an empty state called hours .最初我有一个名为hours的空 state 。 I want to update that state with an array that I put together later on called all_hours .我想用我稍后放在一起的名为all_hours When I do this.state.hours = all_hours , the state gets updated.当我这样做时。 this.state.hours = all_hours , state 得到更新。 However, when I do this.setState({hours:all_hours}) it doesn't get updated.但是,当我这样做时this.setState({hours:all_hours})它没有得到更新。

class DevicesInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hours: []
    };
  }
 

 componentDidMount() {
     // some api calls 
     all_hours = ["12:00 am", "1:00 am", "2:00 am", ... "12:00 pm"];
     this.state.hours = all_hours // correct array printed
     this.setState({hours:all_hours}) // empty array printed
}

Write it this way:这样写:

class DevicesInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hours: []
    };
  }
 all_hours = ["12:00 am", "1:00 am", "2:00 am", ... "12:00 pm"];

componentDidMount() {
    //this.state.hours = this.all_hours ;
    this.setState({hours: [...this.all_hours]}) ;
  }
}

I gave it a quick run in code sandbox and it seems to be working fine, can you provide extra information so I can guide you better.我在代码沙箱中快速运行它,它似乎工作正常,您能否提供额外的信息以便我可以更好地指导您。

here is the link to example on code sandbox for you to check这是代码沙箱上示例的链接,供您检查

https://codesandbox.io/s/focused-haibt-b6pw4?file=/src/App.js https://codesandbox.io/s/focused-haibt-b6pw4?file=/src/App.js

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

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