javascript - 反应useEffect异步警告?
问题描述
我试图摆脱 React 的警告“看起来你写了 useEffect(async () => ...) 或返回了一个 Promise。相反,在你的效果中编写异步函数并立即调用它”。
我一直在参考这篇文章https://www.robinwieruch.de/react-hooks-fetch-data试图摆脱它,但唉,我做不到。
我的使用效果:
useEffect(() => api.getAllPokemon(setResponse),[])
还有我在导入文件中定义的 api.getAllPokemon 异步函数:
const api = {}
api.getAllPokemon = async (cb) => {
await fetch('http://localhost:8080/pokemon', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(async (pokemon) => await pokemon.json())
.then((pokemon) => pokemon.rows.map(({ name }) => name))
.then(pokemon => cb(pokemon))
};
export default api;
解决方案
useEffect
只能返回一个清理函数或什么都不返回。在您的情况下,将括号添加到箭头函数或使用普通函数语法以避免返回 Promise:
useEffect(() => {
api.getAllPokemon(setResponse)
}, [])
或者
useEffect(function () {
api.getAllPokemon(setResponse)
}, [])