简体   繁体   English

从React中的一个单独的.js文件导出由'fetch'返回的数据

[英]Export data returned by 'fetch' from a separate .js file in React

This is my code 这是我的代码

 const data = () => fetch("https://api.myjson.com/bins/mp441") .then(response => response.json()) .then(obj => data = obj); const RECORD_NOS=Object.keys(data).length-1; export {data, RECORD_NOS} 

I am trying to get the json data hosted at the above url, save the data in a variable and export it for use in various places in my React application but unfortunately it gives the following error. 我试图将json数据托管在上述url上,将数据保存在一个变量中,然后将其导出以便在我的React应用程序中的各个位置使用,但是不幸的是,它给出了以下错误。

 ./src/resources/index.js Syntax error: D:/Users/kumahay/Documents/lending-referrals-app/src/resources/index.js: "data" is read-only 1 | const data = () => fetch("https://api.myjson.com/bins/mp441") 2 | .then(response => response.json()) > 3 | .then(obj => data = obj); | ^ 4 | 5 | const RECORD_NOS=Object.keys(data).length-1; 6 | 

I have tried console logging instead of assigning the data but it doesn't work. 我尝试了控制台日志记录而不是分配数据,但是它不起作用。 Apparently the data is not being fetched. 显然数据没有被获取。 How to better frame this code so that it works as expected? 如何更好地构建此代码以使其按预期工作? I am a beginner in javaScript so any help will be appreciated. 我是javaScript的初学者,因此将不胜感激。

I think you should read more about async functions, Promises and fetch. 我认为您应该阅读有关异步功能,Promises和fetch的更多信息。 The best way is export getData function, remove .then(obj => data = obj) and use it in any other module like this 最好的方法是导出getData函数,删除.then(obj => data = obj)并在像这样的任何其他模块中使用它

getData.js getData.js

export const getData = () => fetch("https://api.myjson.com/bins/mp441")
  .then(response => response.json())

anyOtherFile.js anyOtherFile.js

import {getData} from './path/to/getData.js';

export const someFunc = () => {
   getData().then(data => {
       /* do what you want to do in promise resolve callback function */
   })
}

or with async/await notation 或使用异步/等待符号

getData.js getData.js

export const getData = async () => fetch("https://api.myjson.com/bins/mp441")
  .then(response => response.json())

anyOtherFile.js anyOtherFile.js

import {getData} from './path/to/getData.js';

export const someFunc = async () => {
    const data = await getData();
}

Please change the name of data to response data and instead of constant use variable. 请将数据名称更改为响应数据,而不要使用常量变量。 Constant cannot be overwritten but variable can. 常量不能被覆盖,而变量可以。

Example: 例:

var data = "something"; var data =“ something”;

const name ="Japarsathik";

var salary = "$5000";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM