从API获取数据的最佳方法 [英] Best way to fetch the data from API

查看:61
本文介绍了从API获取数据的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个简单的React应用程序,需要在选择下拉列表中显示用户列表.

此用户列表来自api.

因此,我在应用程序中使用了Context API,并创建了一个上下文,并在该上下文中进行了api调用.

context.js

  import从"react"导入React;从"axios"导入axios;导出const UserContext = React.createContext();导出函数Provider({children}){const getUsers =()=>{return axios.get(`https://randomuser.me/api/?results = 10`).then((res)=> {返回资源;});};返回 (< UserContext.Provider value = {{usersList:getUsers()}}>{孩子们}</UserContext.Provider>);} 

users.js

->仅包括获取用户数据并包含

查询:

->可以正常工作,但是在我的实际应用程序中会导致多个api调用.

->我已经检查了网络"标签,该标签已被调用了至少50次,我认为这将是性能方面的一个大问题.

所以我想知道是否有更好的标准方法来实现此目的,以避免内存泄漏和对api提取的多次调用?

我正在怀疑这行,

 < UserContext.Provider value = {{usersList:getUsers()}}> 

导致真正的问题,因为我正在调用带假体() getUsers()方法,但是如果我删除它,它将不会执行..

请帮助我,谢谢.

解决方案

您可以将用户列表存储在数组中,并使组件在挂载时调用 getUsers .然后只需在需要的地方使用 users

 导出函数Provider({children}){const [users,setUsers] = useState([]);const getUsers =()=>{如果(!users.length){axios.get(`https://randomuser.me/api/?results = 10`).然后((res)=> {setUsers(res.data.results);});}};返回 (< UserContext.Provider value = {{usersList:users,getUsers}}>{孩子们}</UserContext.Provider>);} 

在User.js上

  const Users =()=>{const {usersList,getUsers} = useContext(UserContext);useEffect(()=> {getUsers();},[getUsers]);返回 (< div>< p>从API</p>中调用选择框中用户列表下面的内容.<选择值= {"}名称=用户"选项= {用户}getOptionLabel = {(选项)=>option.name.first}getOptionValue = {(option)=>option.id.value}className ="basic-multi-select";/></div>);}; 

I am making a simple react application in which I am in the need to display user list in select dropdown.

This user list comes from api.

So I am using Context API in my application and I have made a context and made the api call inside the context.

context.js

import React from "react";
import axios from "axios";

export const UserContext = React.createContext();

export function Provider({ children }) {
  const getUsers = () => {
    return axios.get(`https://randomuser.me/api/?results=10`).then((res) => {
      return res;
    });
  };

  return (
    <UserContext.Provider value={{ usersList: getUsers() }}>
      {children}
    </UserContext.Provider>
  );
}

users.js

-> Just including context where user data has been fetched and included react-select for dropdown.

-> Using useContext getting the promise value and inside useEffect hook getting the response and storing it in a state variable setUsers

-> In render method returning the select box values with the fetched users list as dropdown.

import React, { useContext, useEffect, useState } from "react";
import Select from "react-select";
import { UserContext } from "../context";

const Users = () => {
  const { usersList } = useContext(UserContext);

  const [users, setUsers] = useState([]);

  const getUsers = () => {
    usersList.then((users) => {
      setUsers(users.data.results);
    });
  };

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

  return (
    <div>
      <p> Below user list in select box is called from API </p>
      <Select
        value={""}
        name="user"
        options={users}
        getOptionLabel={(option) => option.name.first}
        getOptionValue={(option) => option.id.value}
        className="basic-multi-select"
      />
    </div>
  );
};

export default Users;

Working example:

Query:

-> This works fine but in my real application this leads to multiple api calls.

-> I have checked in network tab and it has been called for at least 50 times and I feel that this will be a big issue regarding peroformance.

So I would like to know if there is a much better and standard way of implementing this in order to avoid memory leaks and multiple calls for an api fetch?

I am suspecting whether this line,

<UserContext.Provider value={{ usersList: getUsers() }}>

causing the real issue as I am calling getUsers() method with parathesis () but if I remove it the it doesn't get executed..

Please kindly help me and thanks in advance..

解决方案

You can store the user list in an array, and have your components call getUsers on mount. Then just use users wherever you need

export function Provider({ children }) {
  const [users, setUsers] = useState([]);
  const getUsers = () => {
    if (!users.length) {
      axios.get(`https://randomuser.me/api/?results=10`).then((res) => {
        setUsers(res.data.results);
      });
    }
  };

  return (
    <UserContext.Provider value={{ usersList: users, getUsers }}>
      {children}
    </UserContext.Provider>
  );
}

On User.js

const Users = () => {
  const { usersList, getUsers } = useContext(UserContext);

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

  return (
    <div>
      <p> Below user list in select box is called from API </p>
      <Select
        value={""}
        name="user"
        options={users}
        getOptionLabel={(option) => option.name.first}
        getOptionValue={(option) => option.id.value}
        className="basic-multi-select"
      />
    </div>
  );
};

这篇关于从API获取数据的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆