How to load AJAX in react

2020-07-10 10:58发布

问题:

Im trying to get my json result into my react code

The code looks like the following

_getComments() {

 const commentList = "AJAX JSON GOES HERE"

return commentList.map((comment) => {
  return ( 
           <Comment
           author={comment.author}
           body={comment.body}
           avatarUrl={comment.avatarUrl}
           key={comment.id} />);
  });
}

How do i fetch AJAX into this?

回答1:

First, to fetch the data using AJAX, you have a few options:

  • The Fetch API, which will work out of the box in some browsers (you can use a polyfill to get it working in other browsers as well). See this answer for an example implementation.
  • A library for data fetching (which generally work in all modern browsers). Facebook recommends the following:
    • superagent
    • reqwest
    • react-ajax
    • axios
    • request

Next, you need to use it somewhere in your React component. Where and how you do this will depend on your specific application and component, but generally I think there's two scenarios to consider:

  1. Fetching initial data (e.g. a list of users).
  2. Fetching data in response to some user interaction (e.g. clicking a button to add more users).

Fetching initial data should be done in the life-cycle method componentDidMount(). From the React Docs:

var UserGist = React.createClass({
  getInitialState: function() {
    return {
      username: '',
      lastGistUrl: ''
    };
  },

  componentDidMount: function() {
    this.serverRequest = $.get(this.props.source, function (result) {
      var lastGist = result[0];
      this.setState({
        username: lastGist.owner.login,
        lastGistUrl: lastGist.html_url
      });
    }.bind(this));
  },

  componentWillUnmount: function() {
    this.serverRequest.abort();
  },

  render: function() {
    return (
      <div>
        {this.state.username}'s last gist is
        <a href={this.state.lastGistUrl}>here</a>.
      </div>
    );
  }
});

ReactDOM.render(
  <UserGist source="https://api.github.com/users/octocat/gists" />,
  mountNode
);

Here they use jQuery to fetch the data. While that works just fine, it's probably not a good idea to use such a big library (in terms of size) to perform such a small task.

Fetching data in response to e.g. an action can be done like this:

var UserGist = React.createClass({
  getInitialState: function() {
    return {
      users: []
    };
  },

  componentWillUnmount: function() {
    this.serverRequest && this.serverRequest.abort();
  },

  fetchNewUser: function () {
    this.serverRequest = $.get(this.props.source, function (result) {
      var lastGist = result[0];
      var users = this.state.users
      users.push(lastGist.owner.login)
      this.setState({ users });
    }.bind(this));
  },

  render: function() {
    return (
      <div>
        {this.state.users.map(user => <div>{user}</div>)}
        <button onClick={this.fetchNewUser}>Get new user</button>
      </div>
    );
  }
});

ReactDOM.render(
  <UserGist source="https://api.github.com/users/octocat/gists" />,
  mountNode
);


回答2:

Lets take a look on the fetch API : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Lets say we want to fetch a simple list into our component.

export default MyComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            lst: []
        };

        this.fetchData = this.fetchData.bind(this);
    }

    fetchData() {
        fetch('url')
        .then((res) => {
            return res.json();
        })
        .then((res) => {
            this.setState({ lst: res });
        });
    }
}

We are fetching the data from the server, and we get the result from the service, we convert is to json, and then we set the result which will be the array in the state.



回答3:

You can use jQuery.get or jQuery.ajax in componentDidMount:

import React from 'react';

export default React.createClass({
...
    componentDidMount() {
        $.get('your/url/here').done((loadedData) => {
            this.setState({data: loadedData});
    });
...
}


回答4:

First I'd like to use fetchAPI now install of ajax like zepto's ajax,the render of reactjs is asyn,you can init a state in the constructor,then change the state by the data from the result of fetch.



标签: ajax reactjs