2017-07-25 78 views
0

我想從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')); 

CodePen

+0

你可以肯定的下載失敗?你應該添加一個.catch()來獲取錯誤。例如'取( 'https://randomuser.me/api/') 。然後(響應=> { 如果(!request.ok){ 擲錯誤( 「網絡請求失敗。」) } 返回響應 catch((error)=> {console.log(error);})' –

回答

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

+0

謝謝Shubham提供解決方案和鏈接。我剛剛意識到我正在研究一個不同的文檔。 –

+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) 
}) 
+0

謝謝你的幫助。 –

+0

np mate,我發佈了這個簡單的代碼片段,以便您輕鬆定義「結果」的來源,並且您可以使用它做任何事情,控制檯註銷這些數據是我過去常用的便捷方式。 –

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 
    }) 
+0

謝謝你的幫助。 –