我正在尝试使用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'));
答案 0 :(得分:1)
获取方法应该是
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)
})
答案 1 :(得分:1)
我认为你的问题在于
.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
})
答案 2 :(得分:1)
如GITHUB docs所述,您可以实现类似
的提取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
})
})
<强> CODEPEN 强>