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在实际更新时不会显示更新状态。很高兴我能提供任何帮助:)