【问题标题】:Fetch returns undefined when imported导入时获取返回未定义
【发布时间】:2019-04-24 00:36:04
【问题描述】:

我有一个从 url 获取数据并应该返回它的函数:

const fetchTableData = () => {
fetch('https://api.myjson.com/bins/15psn9')
    .then(result => result.json())
    .then(data => {
        return data;
    })
}

export default fetchTableData;

问题是当我导入这个函数并尝试使用它时,它总是返回undefined

当我控制台记录函数内部的数据时,您可以看到它是可用的。当我尝试导入它时,该功能不起作用。

这里有什么问题?为什么会这样?

【问题讨论】:

  • 你应该在你实现它的地方添加代码

标签: javascript reactjs ecmascript-6 fetch-api


【解决方案1】:

试试这个 =) 你还必须从 fetchTableData 函数返回一些东西。

const fetchTableData = () => {
  const fetchedData = fetch('https://api.myjson.com/bins/15psn9')
    .then(result => result.json())
    .then(data => {
        return data;
    })

    return fetchedData;
}

export default fetchTableData;

或者你可以像这样返回它:

const fetchTableData = () => {
      return fetch('https://api.myjson.com/bins/15psn9')
        .then(result => result.json())
        .then(data => {
            return data;
        })
    }

    export default fetchTableData;

【讨论】:

  • 太棒了,就像一个魅力。谢谢!能否请您提醒一下,这种方式 fetchTableData() 返回一个 Promise 并且需要使用另一个 then 访问它的数据?对于像我这样的其他新手来说,解决这个问题会节省几分钟。
  • componentDidMount() { const data = fetch("localhost:4000/profile/address") .then((res) => { res = res.json(); }) .then((res) => { return res; }); console.log(data); } 控制台显示: Promise {} proto: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: undefined请帮助,在此先感谢
【解决方案2】:

您需要将数据存储在全局变量中或分配任何变量以获取返回数据。

//First way
fetch('https://api.myjson.com/bins/15psn9')
    .then(result => result.json())
    .then(data => {
        console.log("data",data);
    });
    
//Second way
let binData = null;

fetch('https://api.myjson.com/bins/15psn9')
    .then(result => result.json())
    .then(data => {
        binData = data;
        console.log("binData", binData);
    });
    

这是工作示例。

【讨论】:

    【解决方案3】:

    在您的代码中,您没有从 fetchTableData 函数返回。仅来自第二个then() 回调。当函数没有返回值时,会返回undefined

    试试这个:

    const fetchTableData = () => {
    const myResponse = fetch('https://api.myjson.com/bins/15psn9')
        .then(result => result.json())
        .then(data => {
            return data;
        })
    return myResponse;
    }
    
    export default fetchTableData;
    

    现在发生的情况如下:

    1. 第二个then()函数返回的响应是返回数据。
    2. 我们将此数据保存在一个名为 myResponse 的变量中。
    3. 我们现在从函数 fetchTableData 返回这个值。

    【讨论】:

      猜你喜欢
      • 2019-11-11
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      相关资源
      最近更新 更多