简体   繁体   English

React —使用提取请求数据

[英]React — Requesting data using Fetch

I am trying to get some data from an API using Fetch without success. 我试图使用Fetch从API获取一些数据,但没有成功。 For some reason the request is failing and I am not able to render the data... as I am quite new to React and Fetch I am not sure where the error is. 由于某种原因,请求失败,并且我无法呈现数据...因为我对React和Fetch还是很陌生,所以我不确定错误在哪里。 Is it something to do with the way I am requesting the API? 与我请求API的方式有关吗?

Thank you in advance 先感谢您

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 CodePen

fetch method should be 提取方法应为

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

I think your problem is with 我认为您的问题在于

.then(response => {
    if (!request.ok) {
      throw Error("Network request failed.")
    }
    return response
  })

There's no request object that has the property ok . 没有具有ok属性的请求对象。 Maybe you mean to check response.ok ? 也许您想检查一下response.ok

.then(response => {
    if (!response.ok) {
      throw Error("Network request failed.")
    }
    return response
  })

As mentioned on the GITHUB docs , you can implement the fetch like 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 CODEPEN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM