简体   繁体   English

我如何从一开始就在 React 中检索数据 (JSON),然后按照我的意愿将其导出到我的应用程序的任何其他文件中?

[英]How can I retrieve data (JSON) in React from the beginning and then export it as I wish in any other file of my app?

I need to have a file, let's say data.js .我需要一个文件,比方说data.js This file is going to fetch data with async/await fetch() from a MongoDB database.该文件将使用 async/await fetch()从 MongoDB 数据库中获取数据。 I would like to somehow pause the React execution until I have retrieved the data.我想以某种方式暂停React 执行,直到我检索到数据。 Then start the React and export data to any file I wish.然后启动 React 并将数据导出到我想要的任何文件。 I am asking because it is like with async/await my app is executing in a "parallel" way so it seems impossible to assign a promise result in a variable in some point of my app like:我问是因为它就像async/await我的应用程序以“并行”方式执行,所以似乎不可能在我的应用程序的某个点分配一个 promise 结果变量,如:

let data = {};
get_data().then((result) => (data = result));

It just keeps the data variable undefined.它只是保持data变量未定义。

There are various method by which you can do that.有多种方法可以做到这一点。

  • First i guess let variable will only be in functional scope and can't get its value until return.首先,我猜 let 变量只会在功能 scope 中,并且在返回之前无法获取它的值。

  • Second You can declare any setState in your code and use it by exporting that component anywhere you want.其次,您可以在代码中声明任何 setState 并通过将该组件导出到您想要的任何位置来使用它。

  • Third is debouncing method in which you can make your function wait and then use that data in your UI.第三种是去抖动方法,您可以让 function 等待,然后在您的 UI 中使用该数据。

if the result is coming undefiend then idk what you asking for.如果结果是 undefiend 那么 idk 你要求什么。 i wish this helps you.我希望这对你有帮助。

 For debouncing const debounce = (func) => { let timer; return function (...args) { const context = this; if (timer) clearTimeout(timer); timer = setTimeout(() => { timer = null; func.apply(context, args); }, 500); }; }; const handleChange = (value) => { fetch(`https://demo.dataverse.org/api/search?q=${value}`).then((res) => res.json()).then((json) => setSuggestions(json.data.items)); }; const optimizedFn = useCallback(debounce(handleChange), []);

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

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