【发布时间】:2020-07-15 19:05:15
【问题描述】:
我有一个相当棘手的问题。在我的 componentDidMount 方法中,我有:
1.) 在变量“dog”上设置状态
2.) 通过 axios 进行 API 调用,其响应设置另一个变量“dogName”的状态
这会产生问题(我想要呈现给浏览器的数据没有呈现) - 那么有没有更好的方法来编写我的代码?
setData = async () => {
const x = await fetch("https://dog.ceo/api/breed/hound/images");
const y = await x.json();
const z = await y.message;
let newArr = [];
for (let i = 0; i < z.length; i++) {
if (i <= 9) {
newArr.push(z[i]);
}
}
return newArr;
};
componentDidMount() {
this.setState({
loading:true
})
this.setData()
.then(res =>{
this.setState({
loading:false,
dog: res,
})
})
axios.get('http://localhost:3000/dogs')
.then(res => {
this.setState({
dogName:res.data
})
})
.catch(error => {
console.log(error)
})
}
【问题讨论】: