【发布时间】:2017-07-25 08:16:39
【问题描述】:
我正在尝试使用 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'));
【问题讨论】:
-
你能确定抓取失败吗?您应该添加一个 .catch() 来获取错误。例如
fetch('https://randomuser.me/api/') .then(response => { if (!request.ok) { throw Error("Network request failed.") } return response }).catch((error) => { console.log(error);})