在 react js 中执行 API 调用的正确方法是什么?
2022-08-30 02:03:25
						我最近从Angular迁移到ReactJs。我正在使用jQuery进行API调用。我有一个API,它返回一个随机的用户列表,该列表将打印在列表中。
我不确定如何编写我的API调用。最佳做法是什么?
我尝试了以下方法,但我没有得到任何输出。如有必要,我愿意实现替代API库。
以下是我的代码:
import React from 'react';
export default class UserList extends React.Component {    
  constructor(props) {
    super(props);
    this.state = {
      person: []
    };
  }
  UserList(){
    return $.getJSON('https://randomuser.me/api/')
    .then(function(data) {
      return data.results;
    });
  }
  render() {
    this.UserList().then(function(res){
      this.state = {person: res};
    });
    return (
      <div id="layout-content" className="layout-content-wrapper">
        <div className="panel-list">
          {this.state.person.map((item, i) =>{
            return(
              <h1>{item.name.first}</h1>
              <span>{item.cell}, {item.email}</span>
            )
          })}
        <div>
      </div>
    )
  }
}
 
					 
				 
				    		 
				    		