在 react js 中进行 API 调用的正确方法是什么?

新手上路,请多包涵

我最近从 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>
 )
 }
 }

原文由 Raj Rj 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 744
2 个回答

在这种情况下,您可以在 componentDidMount 内部进行 ajax 调用,然后更新 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>
 );
 }
 }

原文由 Oleksandr T. 发布,翻译遵循 CC BY-SA 3.0 许可协议

作为对 Oleksandr T. 出色答案的补充/更新:

  • 如果你使用 类组件,后端调用应该发生在 componentDidMount 中。

  • 如果你改用 钩子,你应该使用 效果钩子

例如:

 import React, { useState, useEffect } from 'react';

 useEffect(() => {
 fetchDataFromBackend();
 }, []);

 // define fetchDataFromBackend() as usual, using Fetch API or similar;
 // the result will typically be stored as component state

进一步阅读:

原文由 sleske 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题