首页 文章

如何在React中处理fetch API AJAX响应

提问于
浏览
4

我正在使用React中的fetch API创建一个简单的AJAX请求,特别是在 componentDidMount() 函数中 .

它正常工作,因为控制台似乎正在记录结果 . 但是,我不知道如何访问响应...

componentDidMount = () => {

      let URL = 'https://jsonplaceholder.typicode.com/users'

         fetch(URL)
         .then(function(response) {
            let myData = response.json()
            return myData;
         })
         .then(function(json) {
            console.log('parsed json', json)
         })
         .catch(function(ex) {
            console.log('parsing failed', ex)
         })

   } // end componentDidMount

我尝试在fetch方法之外访问 myData ,但这会抛出一个错误,说明它是未定义的 . 因此它只能在函数范围内访问 .

然后我尝试了这个:

.then(function(response) {
        let myData = response.json()
        // return myData;
        this.setState({
           data: myData
        })
     })

这一次,我得到 Cannot read property 'setState' of undefined(…)

如何将获取响应传递给状态,甚至只传递全局变量?


更新

import React, { Component } from 'react';
import './App.css';

class App extends Component {

   constructor(props) {
      super(props);
      this.state = {
         data: null
      }
   }

   componentDidMount() {
      let URL = 'https://jsonplaceholder.typicode.com/users'  
         fetch(URL)
         .then( (response) => {
            let myData = response.json()
            // return myData;
            this.setState({
               data: myData
            })
         })
         .then( (json) => {
            console.log('parsed json', json)
         })
         .catch( (ex) => {
            console.log('parsing failed', ex)
         })
         console.log(this.state.data)
   } // end componentDidMount

  render() {
    return (
      <div className="App">
         {this.state.data}
      </div>
    );
  }
}

export default App;

6 回答

  • 1

    REACT NATIVE

    import React, { Component } from 'react';
    
    import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    } from 'react-native';
    
    export default class SampleApp extends Component {
    constructor(props) {
    super(props);
    this.state = {
        data:  'Request '
        }
    }
    
    componentDidMount = () => {
    fetch('http://localhost/replymsg.json', {
                          mode: "no-cors",
                          method: "GET",
                          headers: {
                            "Accept": "application/json"
                          },} )
                          .then(response => {
                          if (response.ok) {
    
                              response.json().then(json => {
    
                                console.warn( JSON.stringify(json.msg ));
                                  this.setState({
                                     data: JSON.stringify(json)
                                })
    
                            });
                          }
                        }); 
    
    }
    
    
    
    render() { 
    return (
        <Text>  {this.state.data}</Text>
        );
        }
    }
    
    AppRegistry.registerComponent('SampleApp', () => SampleApp);
    

    JSON FILE 创建一个文件replymsg.json并放在内容之下,它应该托管到本地主机,如:http://localhost/replymsg.json

    {"status":"200ok","CurrentID":28,"msg":"msg successfully reply"}
    
  • 11

    您需要将当前上下文绑定到目标函数

    fetch(URL)
             .then(function(response) {
                return response.json();
             })
             .then(function(json) {
                this.setState({data: json})
             }.bind(this))
             .catch(function(ex) {
                console.log('parsing failed', ex)
             })
    
  • 6

    使用“=>”而不是函数在同一上下文中更改访问响应数据的方式 .

    componentDidMount = () => {
    
          let URL = 'https://jsonplaceholder.typicode.com/users'
    
             fetch(URL)
             .then(function(response) {
                let myData = response.json()
                return myData;
             })
             .then((json) => {
                console.log('parsed json', json)
             })
             .catch(function(ex) {
                console.log('parsing failed', ex)
             })
    
    } // end componentDidMount
    
  • 2

    就我所见,你有两个问题, response.json() 返回一个承诺,所以你不想将 myData 设置为承诺,而是首先解决承诺,然后你可以访问你的数据 .

    其次, this 在获取请求中不在同一范围内,因此这是您未定义的原因,您可以尝试保存 this 范围以外的获取:

    var component = this;
    
    fetch(URL)
     .then( (response) => {
        return response.json()    
     })
     .then( (json) => {
        component.setState({
           data: json
        })
        console.log('parsed json', json)
     })
     .catch( (ex) => {
        console.log('parsing failed', ex)
     })
     console.log(this.state.data)
    
  • 0

    setState未定义,因为您使用经典函数语法而不是箭头函数 . 箭头函数从'parent'函数中获取'this'关键字,经典函数(){}创建它自己的'this'关键字 . 试试这个

    .then(response => {
        let myData = response.json()
        // return myData;
        this.setState({
           data: myData
        })
     })
    
  • 1

    您使用 this.setState 在正确的轨道上,但是当您在处理响应的函数中调用它时, this 不再位于组件的上下文中 . 使用 => 函数可以维护 this 的上下文 .

    fetch(URL)
        .then((res) => res.json())
        .then((json) => this.setState({data: json}));
    

相关问题