我想從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()來獲取錯誤。例如'取( 'https://randomuser.me/api/') 。然後(響應=> { 如果(!request.ok){ 擲錯誤( 「網絡請求失敗。」) } 返回響應 catch((error)=> {console.log(error);})' –