我最近从Angular转到了ReactJs。我正在使用jQuery进行API调用。我有一个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> ) } }
在这种情况下,您可以在中进行ajax调用componentDidMount,然后进行更新state
componentDidMount
state
export default class UserList extends React.Component { constructor(props) { super(props); this.state = {person: []}; } componentDidMount() { this.UserList(); } UserList() { $.getJSON('https://randomuser.me/api/') .then(({ results }) => this.setState({ person: results })); } render() { const persons = this.state.person.map((item, i) => ( <div> <h1>{ item.name.first }</h1> <span>{ item.cell }, { item.email }</span> </div> )); return ( <div id="layout-content" className="layout-content-wrapper"> <div className="panel-list">{ persons }</div> </div> ); } }