Handling ajax with React

前端 未结 5 1038
南笙
南笙 2020-12-02 13:11

How should I handle ajax requests in a fairly traditional web application? Specifically with using React for views, while having a backend that handles data such as text and

相关标签:
5条回答
  • 2020-12-02 13:48

    Just in case anybody stumbled upon this and does not know, jQuery makes it super easy to send AJAX calls. Since React is just JavaScript it will work just like any other jQuery AJAX call.

    React's own documentation uses jQuery to make the AJAX call so I assume that's good enough for most purposes regardless or stack.

    componentDidMount: function() {
        $.ajax({
          url: this.props.url,
          dataType: 'json',
          cache: false,
          success: function(data) {
            this.setState({data: data});
          }.bind(this),
          error: function(xhr, status, err) {
            console.error(this.props.url, status, err.toString());
          }.bind(this)
        });
      },
    
    0 讨论(0)
  • 2020-12-02 13:56

    You can use JavaScript Fetch API, it supports GET and POST as well, plus it has building Promises.

    fetch('/api/getSomething').then(function() {...})
    
    0 讨论(0)
  • 2020-12-02 14:06

    I would not use JQuery, since AJAX calls is actually not that complex and JQuery is a pretty big dependency. See vanillajs' note on doing AJAX calls without libraries: http://vanilla-js.com/

    0 讨论(0)
  • 2020-12-02 14:07

    Kindly checkout the official documentation of Facebook about Complementary Tools at https://github.com/facebook/react/wiki/Complementary-Tools

    They simply recommends few data fetching API's like

    • axios: Promise based HTTP client for the browser and node.js.
    • jQuery AJAX: No introduction needed.
    • superagent: A lightweight "isomorphic" library for AJAX requests.
    • reqwest: AJAX all over again. Includes support for xmlHttpRequest, JSONP, CORS, and CommonJS Promises A. Browser support stretches back to IE6.

    My personal favorite would be axios due to promises which works in browser as well as in nodejs env and even officially reactJS website recommend the same at AJAX and APIs

    0 讨论(0)
  • 2020-12-02 14:08

    I definitely proffer you to use Fetch API. It is very simple to understand, supports all methods and you can use async/await instead of promise/then and call back hell.

    For example:

    fetch(`https://httpbin.org/get`,{
        method: `GET`,
        headers: {
            'authorization': 'BaseAuth W1lcmxsa='
        }
    }).then((res)=>{
        if(res.ok) {
            return res.json();
        }
    }).then((res)=>{
        console.log(res); // It is like final answer of XHR or jQuery Ajax
    })
    

    In better way or async/await way:

    (async function fetchAsync () {
        let data = await (await fetch(`https://httpbin.org/get`,{
                                    method: `GET`,
                                    headers: {
                                        'authorization': 'BaseAuth W1lcmxsa='
                                    }
                                })).json();
                          console.log(data);
    })();
    
    0 讨论(0)
提交回复
热议问题