【问题标题】:How can I update the state from an API call?如何通过 API 调用更新状态?
【发布时间】:2021-01-04 13:28:09
【问题描述】:

我对我的服务器进行了调用,该服务器期望从该调用返回一个对象。

constructor(props) {
super(props);
this.state ={todos: []};
}
componentDidMount() {
 console.log("HELLO");
 axios.get("http://localhost:4000/todos")
.then(response =>{
  console.log(response.data); // this works
  this.setState({todos: response.data});
  })
 console.log(this.state.todos); // this does not (why?)
 }

【问题讨论】:

标签: reactjs axios state


【解决方案1】:

this.setState({todos: response.data}) 不同步。 console.log(this.state.todos) 可以在 setState 之前执行

来自react文档:

setState() 并不总是立即更新组件。它可能会批量更新或将更新推迟到以后。这使得在调用setState() 之后阅读this.state right 成为一个潜在的陷阱。相反,请使用 componentDidUpdatesetState 回调 (setState(updater, callback)),保证在应用更新后触发其中任何一个。

如果您需要根据之前的状态设置状态,请阅读下面的 updater 参数。

this.setState({todos: response.data},function () {
     console.log(this.state.todos);
});

阅读本文了解更多详情:https://reactjs.org/docs/react-component.html#setstate

【讨论】:

  • 所以我有一些基于此渲染的代码,并且由于某种原因,那里的状态也没有更新。这就是为什么我尝试使用 console.log 调试它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 2021-08-17
相关资源
最近更新 更多