簡體   English   中英

React —使用提取請求數據

[英]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'));

CodePen

提取方法應為

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

CODEPEN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM