Reactjs Can';如果i console.log在axios之外,则看不到我的状态已更新。然后运行
我正试图用Api和Axios调用弄脏我的双手。我有这个问题。在componentDidMount中,我有一个axios调用:Reactjs Can';如果i console.log在axios之外,则看不到我的状态已更新。然后运行,reactjs,axios,Reactjs,Axios,我正试图用Api和Axios调用弄脏我的双手。我有这个问题。在componentDidMount中,我有一个axios调用: componentDidMount() { axios.get("https://api.imgflip.com/get_memes").then(res => { const allMemeImgs = res.data.data.memes; this.setState({ allMemeImgs }); console.log(
componentDidMount() {
axios.get("https://api.imgflip.com/get_memes").then(res => {
const allMemeImgs = res.data.data.memes;
this.setState({ allMemeImgs });
console.log(this.state.allMemeImgs[0]);
});
}
在初始状态下,我声明了一个空数组:
this.state ={
allMemeImgs: []
}
现在,如果我在Axios get请求中登录控制台,我可以看到我的状态已更新。但如果我尝试在外部登录,他们会给我一个错误或一个空数组。因此,这可能意味着状态并没有真正用api数据更新。我错过了什么?
谢谢
设置状态
是异步的,如果您想查看您所做的更改,您必须这样做
componentDidMount() {
axios.get("https://api.imgflip.com/get_memes").then(res => {
const allMemeImgs = res.data.data.memes;
this.setState({ allMemeImgs }, () => {
console.log(this.state.allMemeImgs[0]);
});
});
}
您应该使用setState
回调来保证状态的更改
了解有关
setState
的更多信息当您调用axios.get
时,它将返回一个Promise
承诺不会立即解决。也就是说,当时,执行
块的代码(在承诺得到解决之后)
现在,只要调用axios.get
,就会执行axios之后的console.log
,而不是在收到响应时执行
在这里,您可以在中设置您的状态,然后在块中设置您的状态,如:
axios
.get(url)
.then(response => {
// here you get the response - it may take time for this code to be executed
// set your state here
console.log(response);
}
// this will be executed as your code will not know to wait for the response
console.log(state.response); // you'll not get the response here as this is
// executed before the promise has resolved.
还有一个更简洁的版本-async/await
。如果您能够投入一些时间了解回调、承诺和异步/等待是如何按顺序工作的,那么所有的努力都是值得的