javascript - How to simplify an async call inside a React useEffect Hook
问题描述
I'm trying to create the simplest React Hook useEffect
call I can and hoping not to have to create a function call inside useEffect
. My code is below and it requires me to call fetchData()
to make it work. Is there a simpler version of this?
Maybe with a strategically placed async keyword or something like that?
useEffect(() => {
const fetchData = async () => {
let result = await axios.get('http://localhost:4000/');
console.log(result.data.length);
};
fetchData();
}, []);
解决方案
What you can do is make it an IIFE:
useEffect(() => {
const promise = (async () => {
let result = await axios.get('http://localhost:4000/');
console.log(result.data.length);
})();
return (() => {
promise.then(() => cleanup());
});
}, []);
Or use plain promises:
useEffect(() => {
const promise = axios.get('http://localhost:4000/').then((result) => {
console.log(result.data.length);
});
return (() => {
promise.then(() => cleanup());
})
}, []);
But that is about as much as you can do since useEffect cannot be async directly. From ESLint:
Effect callbacks are synchronous to prevent race conditions.
推荐阅读
- django - 序列化时保持json数据的顺序
- sql - 根据 Oracle 数据库中不同表中存在的列列表选择列?
- javascript - React.Intl 子字符串来自
- vector - 为什么 &[T] 参数也接受 &Vec
? - r - 插图的解释
- angular - Angular 2:登录后如何将用户重定向到以前的 URL
- android - 无法解析符号“?selectableItemBackgroundBorderless”
- node.js - 节点 Koa cors 不工作
- react-native - 我无法使用 react-native 地图在我的 android 上查看地图
- git - 从 git 中的提交消息中获取文件名