Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript this.setState不更新初始空状态数组_Javascript_Reactjs - Fatal编程技术网

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

Javascript this.setState不更新初始空状态数组,javascript,reactjs,Javascript,Reactjs,最初我有一个空状态,名为hours。我想用一个数组来更新这个状态,这个数组后来被称为all\u hours。当我执行this.state.hours=all_hours时,状态会得到更新。但是,当我执行this.setState({hours:all_hours})时,它不会得到更新 class DevicesInfo extends React.Component { constructor(props) { super(props); this.state = {

最初我有一个空状态,名为
hours
。我想用一个数组来更新这个状态,这个数组后来被称为
all\u 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
}

这样写:

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

我在代码沙盒中快速运行了它,它似乎工作得很好,您能否提供额外的信息,以便我可以更好地指导您

下面是代码沙盒上示例的链接,供您检查


你怎么知道它有效/无效?因为就屏幕上显示的内容而言,您说的第一个“工作”非常不起作用……您在组件中调用的
this.setState()
?@redouglas为缺少详细信息表示歉意。我用我调用它的地方(在
componentDidMount()
)更新了原始帖子。如果您只是在
console.log
调用后立即进行检查,则不会显示更新的状态,因为它会异步更新。这是否回答了您的问题?谢谢你!似乎我的问题在于不理解
console.log
ing在实际更新时不会显示更新状态。很高兴我能提供任何帮助:)