javascript - React-Native onSubmitEditting 花费太多时间来执行功能
问题描述
我正在关注一个 react-native 教程,但是在使用 React 上下文和 ActivityIndicator 时遇到了一些问题,我不知道问题出在哪里,但我会尽可能地描述性。
问题:-
代码:
我正在使用上下文为应用程序提供已搜索的位置,然后在我的模拟数据中搜索该位置,然后返回该位置周围的餐馆。
完整的源代码位于https://github.com/diivi/KiloBite/blob/main/src/services/location/location.context.js
在这里我使用 onSearch 函数并将其作为上下文道具传递给我的搜索框与 onSubmitEditing 一起使用。
解决方案
在您调用的代码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);
});
};
推荐阅读
- npm - npm 错误!在“...”附近解析时 JSON 输入意外结束:{“shasum”:“ae6c2edf”
- android - 如何解决工作管理器的多实例问题?
- laravel - React-Native TypeError: Undefined is not an object (评估 this.state.signatures.length)
- reactjs - 使用 ReactJS -> Express 还是使用 Express -> ReactJS 更好?
- python - Keras 给中间层输入,得到最终输出
- sql-server - SQL Server 可以自己执行基于哈希的行相等(用于 MERGE 操作)吗?
- javascript - 无法使用带有 webpack 和 ES6 设置的 document.getElementById('password').addEventListener() 调用函数
- postgresql-9.6 - 读取表时,出现错误:无法访问文件“$libdir/postgis-2.3”:没有这样的文件或目录
- scala - Rhino:如何在没有线程关联的情况下创建上下文
- flutter - 使用 Stacks 在页面之间保存状态时进行动画转换