Asynchronous xmlhttp request in react

后端 未结 4 1321
感动是毒
感动是毒 2021-02-10 05:16

I am trying to implement asynchronous XMLHttpRequest in react. Here is my attempt:

4条回答
  •  逝去的感伤
    2021-02-10 05:29

    It is recommended to make AJAX calls in the componentDidMount lifecycle method.

    componentDidMount is for side effects. Adding event listeners, AJAX, mutating the DOM, etc.

    Also, you should consider using the new fetch API.

    class Welcome extends React.Component {
      constructor() {
        this.state = {
          data: null,
        };
      }
    
      componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/photos/').then(res => {
          return res.json()
        }).then(res => {
            this.setState({ data: res});
        }).catch(err);
      }
    
      render() {
        if (this.state.data) {
          return 
        }
        else {
          return 
    Loading...
    } } }

提交回复
热议问题