如何在带有异步调用的React中使用API? [英] How to use APIs in React with Asynchronous calls?
问题描述
所以我想让我的手被React弄脏.我非常确定要使用ReactJS编写 wikipedia查看器项目.但是,昨天在使用React组件从Wikipedia的API中获取数据后,我碰到了一堵砖墙.而且我认为这与异步调用有关.
So I am trying to get my hands dirty with React. I am VERY determined to write the wikipedia viewer project using ReactJS. However, I hit a brick wall yesterday after fetching the data from wikipedia's API using React components. And I think it has something to do with the asynchronous call.
我定义了一个接受查询并将其注入API URL的常量: javascriptconst apiUrl =查询=>`https://crossorigin.me/https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=$ {query}`
然后,我定义了一个在ComponentDidMount状态下异步获取API的类:
I defined a constant that takes in a query and injects it into the API url:
javascript
const apiUrl = query =>
`https://crossorigin.me/https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=${query}`
Then I defined a class that fetches the API asynchronously in the ComponentDidMount state:
class Wiki extends React.Component {
constructor(props){
super(props);
console.log('Inside Constructor')
}
componentWillMount(){
this.setState = {
wikiData: undefined
}
console.log('Before fetch')
fetch(apiUrl(this.props.query))
.then(console.log('fetch successful'))
.then(response => {
if(!response.ok){
throw Error("Response not ok")
}
return response
})
.then(data => data.json())
.then(data => {
this.setState ={
wikiData: data
}
console.log(data)
})
}
render(){
if(!this.state.wikiData == null) return <p>No answer</p>
else{
return (
<div>
<h1>Something happened</h1>
<h2>{this.state.wikiData[0]}</h2>
</div>
)
}
}
}
当我在应用程序组件中调用此函数时,我收到一个TypeError消息,提示无法读取null的'wikiData'属性",此后数据从调用返回并且不再为null,但这会导致渲染中断.控制台消息我确实尝试使用componentDidMount代替,但这也不起作用.我不知道该怎么办,我想了解这个过程.这是我的codepen: https://codepen.io/Banhawy/pen/eEmQBW?editors=1010
When I call this in the app component, I get a TypeError sying "Cannot read property 'wikiData' of null" after which the data returns from the call and is not null anymore, but that causes the rendering to break. Console messaqges I did try using componentDidMount instead but that doesn't work either. I don't know what to do and I want to get an understanding of this process. Here's my codepen : https://codepen.io/Banhawy/pen/eEmQBW?editors=1010
我想知道如何仅在对API的调用返回了数据之后才渲染组件,以便我可以在渲染之前对其进行访问和处理.
I want to know how to render the component only after the call to the API has returned with data so I can access and process it before rendering.
推荐答案
我对您的代码做了一些修改,并提出了一些意见,希望对您有所帮助.
I've amended your code a bit, and made some comments that will hopefully help you out.
class Wiki extends React.Component {
constructor(props) {
super(props);
// this.state, not this.setState.
// Also, it helps if you set your initial value to the value
// to what you expect from your fetch (ie an array, albeit empty)
this.state = { wikiData: [] }
}
// componentDidMount rather than componentWillMount
// https://daveceddia.com/where-fetch-data-componentwillmount-vs-componentdidmount/
componentDidMount() {
fetch(apiUrl(this.props.query))
.then(response => {
.then(data => data.json())
.then(data => this.setState = { wikiData: data }
});
}
render() {
// Check to see if your initial state is empty or not
if (!this.state.wikiData.length) return <p>No answer</p>
// No need for your else here. If your state is not empty, the first
// return doesn't run, but this one does as a default.
return (
<div>
<h1>Something happened </h1>
<h2>{this.state.wikiData[0]}</h2>
</div>
)
}
}
这篇关于如何在带有异步调用的React中使用API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!