[英]React — Requesting data using Fetch
我试图使用Fetch从API获取一些数据,但没有成功。 由于某种原因,请求失败,并且我无法呈现数据...因为我对React和Fetch还是很陌生,所以我不确定错误在哪里。 与我请求API的方式有关吗?
先感谢您
class App extends React.Component {
render() {
return <Data />
}
}
class Data extends React.Component {
constructor(props) {
super(props)
this.state = {
requestFailed: false,
}
}
componentDidMount() { // Executes after mouting
fetch('https://randomuser.me/api/')
.then(response => {
if (!request.ok) {
throw Error("Network request failed.")
}
return response
})
.then(d => d.json())
.then(d => {
this.setState({
data: d
})
}, () => {
this.setState({
requestFailed: true
})
})
}
render() {
if(this.state.requestFailed) return <p>Request failed.</p>
if(!this.state.data) return <p>Loading</p>
return (
<h1>{this.state.data.results[0].gender}</h1>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
提取方法应为
fetch('your_url')
.then (
response => {
if (response.status !== 200) {
return 'Error. Status Code: ' + response.status
}
response.json().then(result => console.log(result)) // do sth with data
}
)
.catch(function(err) {
console.log('Opps Error', err)
})
我认为您的问题在于
.then(response => {
if (!request.ok) {
throw Error("Network request failed.")
}
return response
})
没有具有ok属性的请求对象。 也许您想检查一下response.ok ?
.then(response => {
if (!response.ok) {
throw Error("Network request failed.")
}
return response
})
如GITHUB文档所述 ,您可以像
fetch('https://randomuser.me/api/')
.then((response) => {
return response.json()
}).then((d) => {
console.log('parsed json', d)
this.setState({
data: d
});
}).catch(function(ex) {
console.log('parsing failed', ex)
this.setState({
requestFailed: true
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.