【问题标题】:React native, setTimeout gives weird warning when called inside useEffectReact Native,setTimeout 在 useEffect 内部调用时会发出奇怪的警告
【发布时间】:2020-07-09 19:54:37
【问题描述】:

如果在应用执行 X 秒后满足某个条件,我最终希望向用户显示一个模式。

但是,我不断收到关于在 android 上长时间(几分钟)设置计时器的警告,但我的计时器只有几秒钟。

const surveyCheckTime = 3000; // X = 3 seconds

const App = () => {
  // First Time Modal State
  const [surveyVisibility, setSurveyVisibility] = useState(false);
  const handleSurveyOpen = () => {
    setSurveyVisibility(true);
  };
  const handleSurveyClose = () => {
    setSurveyVisibility(false);
  };

  useEffect(() => {
    const timer = setTimeout(() => {
      console.log('0:FROM_APP: Checking for condition: ');
      getData().then(
        keyValue => {
          console.log('0:FROM_APP: Completion status: ', keyValue);
          if (keyValue === 'false' || keyValue === undefined) {
            handleSurveyOpen();
          }
        },
        error => {
          // console.log('Survery_Error: ', error);
        },
      );
    }, surveyCheckTime);

    return () => clearTimeout(timer);
  }, []);

  return (
      <View>
         ...
        <SurveyModal
          surveyVisibility={surveyVisibility}
          handleSurveyClose={handleSurveyClose}
        />
      </View>
  )

getData() 是一个异步函数,将 keyValue 作为 promise 返回。

export const getData = async (myKey = 'alreadyOpened') => {
  try {
    const value = await AsyncStorage.getItem(`@${myKey}`);
    if (value !== null) {
      // value previously stored
      // console.log('FROM__getData: Stored previously: ', value);
      return value;
    }
  } catch (e) {
    // error reading value
    console.log('ERROR:FROM__getData: Cannot read: ', e);
    return 'fasle';
  }
};

一切都很好,一切都按预期工作,但我每次都收到这个警告,最后一行不同:

(看到 setTimeout 持续时间为 Y 毫秒)Y 远高于我的 X 值

this 的问题,但在我的情况下它与firebase 并不完全相关。 (虽然我确实使用 firebase 在另一个组件中获取数据,但 这不应该是问题这是问题

我研究了this,但大多数解决方案要么更改“node_modules”,要么禁用警告,而且主题已经过时了。

最好有更有效的超时处理解决方案。

编辑:“firebase”:“7.13.1”是导致获取数据时出现问题的原因

【问题讨论】:

  • getData() 在哪里?可能延迟时间太长了???‍♂️
  • 现在应该可以了,我认为不会花很多时间,因为数据是在本地存储的
  • 如果你的getData() 是一个异步函数,通常你必须在你的计时器上说,因为你的getData() 函数是一个异步函数。示例:javascript const timer = setTimeout(() =&gt; { // not this const timer = setTimeout(async () =&gt; { // this useEffect 也是如此)
  • 不应该 .then() 就足够了吗?如果不是你建议我改变什么。编辑:我会试一试
  • 尝试为useEffecttimergetData().then()设置async值,这可能是问题

标签: reactjs react-native settimeout use-effect


【解决方案1】:

我正在使用导致此问题的已弃用的 firebase 集成(Web 配置而不是 .json 文件)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2021-12-07
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多