【问题标题】:Return data from Async function React Native Redux从异步函数 React Native Redux 返回数据
【发布时间】:2022-01-26 03:25:08
【问题描述】:

在 Expo 中使用 SecureStore 获取数据以获取 react-native 后,我无法访问数据。

下面是简单的代码:

const infoofuser = SecureStore.getItemAsync('userInfo').then(value =>
  console.log(`this is the vlaue from infouser: ${value}`),
);
console.log(`infoouser: ${JSON.stringify(infoofuser)}`);

第一个infoofuser 常量定义返回预期数据的对象。

console.log(`infoouser: ${JSON.stringify(infoofuser)}`);

然而返回{"_U":0,"_V":0,"_W":null,"_X":null} 你理解这是一个承诺。我想简单地获取来自 SecureStore 调用的数据,并使用它在 redux 中设置我的 initialState。

const infoofuser = SecureStore.getItemAsync('userInfo').then(value =>
  value
);

这也不能访问数据

【问题讨论】:

    标签: reactjs react-native asynchronous redux async-await


    【解决方案1】:

    您可以通过 async/await 使用异步方法。试试这个:

    const userInfo = useSelector(state => state.userInfo);
    
    const getData = async () => {
      try {
        const infoofuser = await SecureStore.getItemAsync('userInfo');
        console.log('infoofuser:', infoofuser)
        /// strore on redux
      } catch (err) {
         // handle error
      }
    }
    
    useEffect(() => {
      getData()
    }, [])
    
    if (!userInfo) return null
    
    //render something else
    

    您可以查看Expo Secure Store 文档以供参考。

    【讨论】:

    • 对不起,我的问题是指如何获得 getData() 函数的结果,然后在其他地方使用它。这种方法在我可以看到infoofuser 的值的意义上起作用,但是当let a = getData().then(value => value) 仍然导致承诺时
    • 我可以知道为什么你需要 .then 当我们直接使用 async/await 接收数据时??
    • 您需要在 getData 之前放置 await ,否则您正在分配异步函数的引用,您不会等待异步函数(即:getData)从安全存储中解析数据跨度>
    • 原因是我想在其他地方使用我从异步调用中获得的对象,并将其设置为 redux 中的初始状态。这是根据您的建议的代码:let a = async () => await getData(); console.log(this is a: ${a});
    • 结果如下:this is a: function a() { return _regenerator.default.async(function a$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return _regenerator.default.awrap(getData()); case 2: return _context3.abrupt("return", _context3.sent); case 3: case "end": return _context3.stop(); } } }, null, null, null, Promise); }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 2015-04-21
    • 1970-01-01
    • 2021-02-13
    相关资源
    最近更新 更多