【问题标题】:Fetching api data in one file and use in another component在一个文件中获取 api 数据并在另一个组件中使用
【发布时间】:2022-11-24 19:52:25
【问题描述】:

我像这样从 api 获取数据

import axios from 'axios'

const baseUrl = `${process.env.REACT_APP_URL}/search/users?q=john&per_page=5`

export function fetchData(){
    axios({
          method: "get",
          headers: { "Content-Type": "application/json" },
          url: baseUrl,
        })
          .then(function (response) {
            return response.data;
            
          })
          .catch(function (error) {
            return error;
            
          })
          
    }

并调用到另一个文件

import {fetchData} from '../../api/service'

 const dataVal =  fetchData()
  console.log("data",dataVal)

在控制台中未定义

我期待从 api 获取数组数据

【问题讨论】:

  • 函数中没有return

标签: reactjs


【解决方案1】:

您必须像这样添加 return

export function fetchData() {
  return axios({
    method: "get",
    headers: { "Content-Type": "application/json" },
    url: baseUrl,
  })
    .then(function (response) {
      return response.data;
    })
    .catch(function (error) {
      return error;
    });
}

【讨论】:

    【解决方案2】:

    您需要像这样更新您的代码

    第 1 页)

    import axios from 'axios'
        
        const baseUrl = `${process.env.REACT_APP_URL}/search/users?q=john&per_page=5`
        
        export  function fetchData(){
           return axios({
                  method: "get",
                  headers: { "Content-Type": "application/json" },
                  url: baseUrl,
                })
                  .then( (response) => response.data
                    
                  )
                  .catch( (error)=> 
                    error
                    
                  )
                  
            }
    

    第2页)

    import {fetchData} from '../../api/service'
    
     fetchData().then(res=>{console.log("data",res})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-08
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      • 1970-01-01
      • 2020-11-18
      相关资源
      最近更新 更多