javascript - 如何在 React 组件内的另一个函数中访问 useEffect 的异步数据
问题描述
我有一个带有 Hooks 的功能组件:
const Filters = () => {
const [options, setOptions] = useState([]);
const getOption = type => options.find(el => el.name === type);
useEffect(() => {
fetch('someURL')
.then(resp => resp.json())
.then(result => setOptions(result.data), error => console.log(error));
// trying to check options array now
console.log(getOption('type')); // returns undefined
}, []);
}
这种方法的目的是获取数据,然后通过计算函数运行该数据,以获取基于getOption(type)
. 如果我使用,那么我将获得带有输出的useEffect(() => fetch(), [options]);
无限循环。console.log()
所以,setOptions(result.data)
我猜是异步的,就像setState
在类组件中一样,但不接受在异步请求完成时使用的第二个参数。
我想在我的函数完成options
后修改我的数组。fetch()
getOption()
解决方案
您可以在修改时使用另一个useEffect
执行功能options
:
const Filters = () => {
const [options, setOptions] = useState([]);
const getOption = type => options.find(el => el.name === type);
useEffect(() => {
fetch('someURL')
.then(resp => resp.json())
.then(result => setOptions(result.data), error => console.log(error));
}, []);
useEffect(() => {
if (!options) {
return;
}
console.log(getOption('type'));
}, [options])
}
推荐阅读
- amazon-web-services - 通过 nginx 连接 AWS S3
- flutter - 如何解决此错误错误:无法解析包
- direct-line-botframework - 无法从直线连接到酱实验室
- c - 优化 C 中的排列代码以在时间限制内运行
- php - 无法使用 PHP 将数据插入 sqlite3 数据库
- java - VS Code & WSL2 - 将 Java 语言级别指定为 1.8
- c++ - 如果从脚本运行应用程序,则在 linux 中使用 GDB
- python - 如何使用第三倍频程(1/3)频带中心频率而不是python中的默认窄带绘制音频文件的频谱图?
- c - 如何只显示一次消息?
- c - 为什么在无法访问时我仍然可以访问内存