首页 > 解决方案 > React-Native onSubmitEditting 花费太多时间来执行功能

问题描述

我正在关注一个 react-native 教程,但是在使用 React 上下文和 ActivityIndi​​cator 时遇到了一些问题,我不知道问题出在哪里,但我会尽可能地描述性。

问题:-
在此处输入图像描述

代码:
我正在使用上下文为应用程序提供已搜索的位置,然后在我的模拟数据中搜索该位置,然后返回该位置周围的餐馆。
完整的源代码位于https://github.com/diivi/KiloBite/blob/main/src/services/location/location.context.js 在这里我使用 onSearch 函数并将其作为上下文道具传递给我的搜索框与 onSubmitEditing 一起使用。

标签: javascriptreactjsreact-nativeexpo

解决方案


在您调用的代码onSearch中,您setILoading(true)setKeyword(searchKeyword).

然后在useEffect你使用keyword你设置的onSearch。您useEffect仅在keyword更改中运行(请参阅依赖项)。

尝试添加onSearch您的依赖项(如下所示)。或者甚至locationRequest, locationTransform。我也会尝试setIsLoading并且通常尝试将您在useEffect.

const onSearch = (searchKeyword) => {
    setIsLoading(true);
    setKeyword(searchKeyword);
  };

  useEffect(() => {
    if (!keyword.length) {
      return;
    }

    locationRequest(keyword.toLowerCase())
      .then(locationTransform)
      .then((result) => {
        setIsLoading(false);
        setLocation(result);
      })
      .catch((err) => {
        setIsLoading(false);
        setError(err);
      });
  }, [keyword, onSearch]);

但是,最后我想知道,你为什么使用 a useEffect?您为什么不将所有代码移入onSearch

const onSearch = (searchKeyword) => {
    setIsLoading(true);
    // setKeyword(searchKeyword); // not needed
if (!searchKeyword.length) {
      return;
    }
    locationRequest(searchKeyword.toLowerCase())
      .then(locationTransform)
      .then((result) => {
        setIsLoading(false);
        setLocation(result);
      })
      .catch((err) => {
        setIsLoading(false);
        setError(err);
      });
  };


推荐阅读