如何立即更新状态变量

时间:2019-06-18 13:54:29

标签: reactjs

我应该如何编码,以便可以立即将API响应保存到状态,并在setState()之外访问更新后的响应。

state={
 response: []
}

this.setState({
  response: res // res is coming from API response
});
console.log(this.state.response); // it should show the API response instead of empty []

3 个答案:

答案 0 :(得分:1)

使用回调:

...
this.setState({
  response: res // res is coming from API response
}, function() {
  console.log(this.state.response);
});
...

答案 1 :(得分:0)

使调用setState的方法异步,然后让res等待答案。像

yourMethod = async (params) => {
  const res = await //api call
  this.setState({
    response: res
  )}
}

答案 2 :(得分:0)

componentDidMount是建议的生命周期挂钩,用于获取初始状态数据

class App extends React.Component {
  state = {
    data: [],
  }

  async componentDidMount() {
    const res = await fetch(url);
    const data = await res.json();
    this.setState({ data }, console.log('state updated', this.state));
  }

  render() {
    return (
      /* render data */
    );
  }
}
相关问题