this.setState不更新初始空状态数组

时间:2020-07-09 23:48:50

标签: javascript reactjs

最初,我的状态为hours。我想用一个以后将其放到一起的数组all_hours来更新该状态。当我执行this.state.hours = all_hours时,状态会更新。但是,当我执行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
}

2 个答案:

答案 0 :(得分:0)

这样写:

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]}) ;
  }
}

答案 1 :(得分:0)

我在代码沙箱中快速运行了它,它似乎运行良好,能否提供更多信息,以便我更好地指导您。

这是代码沙箱上的示例链接,供您检查

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