我正在尝试通过创建函数来获取数据。在该函数中,我正在尝试设置状态,并且从 componentDidMount
调用它。方法,但我遇到了一些问题:
- 我不确定是否
while
这是一个很好的实践,因为我正在循环并更改我的端点,这样我每次都可以获得新数据。 - 我尝试从获取函数返回数据并使用
setState
里面componentDidMount
,但我遇到了问题,我怀疑是因为componentDidMount
在获取完成之前正在运行 - 我尝试过使用
res.json()
使用 promise 对数据进行处理,但我收到错误res.json
不是一个函数。
state = {
title: [],
image: [],
rating: [],
};
getData = () => {
let i = 1;
while (i <= 9) {
axios.get(`http://api.tvmaze.com/shows/${i}`)
.then(response => console.log(response))
.then(response => this.setState({
title:response.data.data.name[i],
}))
.catch(error => console.log(error));
i++;
}
};
componentDidMount() {
this.getData();
console.log(this.state.title);
}
最佳答案
如果您的目标是在获取信息后渲染您的 JSX
,那么我建议您在 state
中创建一个附加项目,isLoading
,您可以将其设置为 true
或 false
并有条件地渲染您的 JSX
。
根据您在下面提供的示例,它看起来如下所示:
class Shows extends React.Component {
state = {
title: [],
image: [],
rating: [],
isLoading: true
}
componentDidMount() {
this.getData()
}
getData = () => {
// I've created a URL for each request
const requestUrls = Array.from({ length: 9 })
.map((_, idx) => `http://api.tvmaze.com/shows/${idx + 1}`);
const handleResponse = (data) => {
// `data` is an array of all shows that you've requested
// extract information about each show from the payload
const shows = data.map(show => show.data)
// handle shows data however you need it
// and don't forget to set `isLoading` state to `false`
this.setState({
isLoading: false,
title: shows.map(show => show.name),
image: shows.map(show => show.url),
rating: shows.map(show => show.rating.average),
})
}
const handleError = (error) => {
// handle errors appropriately
// and don't forget to set `isLoading` to `false`
this.setState({
isLoading: false
})
}
// use `Promise.all()` to trigger all API requests
// and resolve when all requests are completed
Promise.all(
requestUrls.map(url => axios.get(url))
)
.then(handleResponse)
.catch(handleError)
}
render() {
const { isLoading, title, image, rating } = this.state
// prevent showing your `JSX` unless data has been fetched
// ideally, show a loading spinner or something that will
// tell users that things are happening;
// returning `null` won't render anything at all
if (isLoading) {
return null
}
return (
<div>...</div>
)
}
}
这样,使用 Promise.all
,就可以更轻松地推理您正在进行的所有这些调用。
除此之外,使用 componentDidMount
从 API 获取数据是正确的位置,但我会远离 while
循环并使用 Promise.all
用于所有请求,并 map
创建一组可传递给 Promise.all
并在以下位置处理的 promise (请求)一次。
工作示例:
关于javascript - 获取数据之前的渲染组件已经完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57540211/