我应该如何编码,以便可以立即将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 []
答案 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 */
);
}
}