繁体   English   中英

React-Native 从 AsyncStorage 检索 API_URL 并在所有应用程序中访问(用于测试目的)

[英]React-Native retrieve API_URL from AsyncStorage and make in accessible in all app (for test purpose)

我正在尝试从 AsyncStorage 检索 API_URL 并使其在所有应用程序中都可访问,存储和检索(在设置屏幕中)工作正常但是当我尝试使用 useEffect 挂钩将数据加载到 App.js 中时,它返回 null。重新加载应用程序不起作用,但只要我保存 App.js(使用 CTRL-S)它就可以正常工作。 请让我知道执行此操作的正确方法。

import React, { useEffect, useState } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";

export default function App() {


  const [hostState, setHostState] = useState(null);

  const getAHostInfoAsync = async () => {
    const hostInfo = AsyncStorage.getItem('host').then(
      setHostState(hostInfo)
    ).then(
      console.log(hostState)
    );


  };

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

  module.exports = {
    host: hostState
  };


}

并在另一个文件中使用:

import App from "../../../App";
const API_URL = App.host;

我认为您的问题在于您使用 async/then 的方式。 而不是异步等待。 我不是 100% 确定这是你的问题。 但是,如果我将我的 async/await function 更改为使用 async/then 你的方式,我的 IDE 表示变量 (hostInfo) 可能尚未初始化。 无论如何,我认为这是比 then 更好的语法。

const getAHostInfoAsync = async () => {
    const hostInfo = await AsyncStorage.getItem('host')
    setHostState(hostInfo)
    console.log(hostState)
  };

暂无
暂无

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

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