【问题标题】:Async/Await Issue in ReactNativeReact Native 中的异步/等待问题
【发布时间】:2021-04-13 16:30:47
【问题描述】:

在我的 Expo 上,我收到以下错误:

我认为这是由于我的代码中存在 Async/Await 问题,但我不确定如何修复它。我是 ReactNative 的新手,正在学习 Stephen 的 Complete React 课程,但他根本没有讨论这个问题,因此非常感谢任何帮助。

这是我的代码:


import { useEffect, useState } from 'react'
import yelp from '/Users/macbook/Coding Stuff React Native/food/src/api/yelp.js'

export default () => {
  const [results, setResults] = useState([]);
  const [errorMessage, setErrorMessage] = useState('');

  const searchApi = async searchTerm => {
    console.log('Hi there!');
    try {
      const response = await yelp.get('/search', {
        params: {
          limit: 50,
          term: searchTerm,
          location: 'san jose'
        }
      });
      setResults(response.data.businesses);
    } catch (err) {
      setErrorMessage('Something went wrong');
    }

  };

  // Call searchApi when component
  // is first rendered.  BAD CODE!
  // searchApi('pasta');
  useEffect(() => {
    searchApi('pasta');
  }, [])

  return [searchApi, results, errorMessage];
};

谢谢你:)

【问题讨论】:

  • const response = async ....; 表示response 将成为Promise。
  • 是的,我在网上看到过这个。代码是否有修复程序来使用它?感谢您的回复!
  • 您需要在 response.then(() => { ... }) 中执行您的逻辑,一旦承诺解决,该逻辑就会执行。
  • 我相信问题不在这部分代码中。与 react 不同,react native 中的字符串只能在 标记内呈现。
  • 你能在你用过的地方添加更多代码吗?

标签: javascript node.js react-native async-await


【解决方案1】:

为其他坚持此问题的人更新:

我需要改变

{errorMessage ? <Text>{errorMessage}</Text> : null}

到

{!!errorMessage && <Text>{errorMessage}</Text>}

【讨论】:

  • 你能解释一下为什么这能解决你的问题吗?
  • 我没有。我想可能是因为当我在另一个文件中调用这个 const 时,searchApi 完成的速度不够快,所以它正在将 {errorMessage} 作为字符串读取,因为它没有及时被放入函数中。这样做会使其成为三元表达式,但我不确定为什么会有所帮助。我是 ReactNative 的新手。
猜你喜欢
  • 1970-01-01
  • 2018-12-09
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 2019-07-02
  • 2021-06-16
  • 1970-01-01
相关资源
最近更新 更多