【问题标题】:React — Requesting data using FetchReact - 使用 Fetch 请求数据
【发布时间】: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'));

CodePen

【问题讨论】:

  • 你能确定抓取失败吗?您应该添加一个 .catch() 来获取错误。例如fetch('https://randomuser.me/api/') .then(response =&gt; { if (!request.ok) { throw Error("Network request failed.") } return response }).catch((error) =&gt; { console.log(error);})

标签: api reactjs fetch


【解决方案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

【讨论】:

  • 感谢 Shubham 提供的解决方案和链接。我刚刚意识到我正在查看不同的文档。
  • 没问题,乐于助人:)
【解决方案2】:

fetch 方法应该是

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

【讨论】:

  • 感谢您的帮助。
  • np 伙计,我发布了这个简单的 sn-p 以便您轻松定义“结果”的来源,您可以用它做任何事情,控制台注销这些数据是我使用的便捷方式去做。
【解决方案3】:

我认为你的问题出在

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

没有 request 对象具有 ok 属性。也许您的意思是检查 response.ok

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

【讨论】:

  • 感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2015-07-06
  • 2021-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-09
相关资源
最近更新 更多