Javascript 响应Useffect异步警告?
我试图摆脱React的警告“看起来您编写了useEffect(async()=>…)或返回了一个承诺。相反,在您的效果中编写异步函数并立即调用它” 我一直在引用这篇文章试图摆脱它,但唉,我无法做到 我的作用是:Javascript 响应Useffect异步警告?,javascript,reactjs,debugging,asynchronous,react-hooks,Javascript,Reactjs,Debugging,Asynchronous,React Hooks,我试图摆脱React的警告“看起来您编写了useEffect(async()=>…)或返回了一个承诺。相反,在您的效果中编写异步函数并立即调用它” 我一直在引用这篇文章试图摆脱它,但唉,我无法做到 我的作用是: useEffect(() => api.getAllPokemon(setResponse),[]) 以及我在导入文件中定义的api.getAllPokemon异步函数: const api = {} api.getAllPokemon = async (cb) =>
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;
useffect
只能返回清理功能或不返回任何内容。在您的情况下,请将括号添加到箭头函数或使用普通函数语法以避免返回承诺:
useEffect(() => {
api.getAllPokemon(setResponse)
}, [])
或
你不能把等待和承诺结合起来 而且useffect中的async也有一些不同 当您异步获取时,则不起作用,但它会为您返回响应 所以我们需要写一篇文章,试着抓住
useEffect(() => {
try {
const fetchData = async () => {
const res = await fetch("http://localhost:8080/pokemon");
setBaseExperience(res);
};
fetchData();
} catch (err) {
console.log(err);
}
}, []);
使用fetch包装器()的JSON获取示例 在功能部件主体内:
useAsyncEffect(function*(){
const names= yield* api.getAllPokemon(setResponse);
// changeState here
},[])
我没有足够的街头信条,所以我的投票无法公开,但你可以接受答案
import React, { useState } from "react";
import { useAsyncEffect } from "use-async-effect2";
import cpFetch from "cp-fetch"; //cancellable c-promise fetch wrapper
export default function TestComponent(props) {
const [text, setText] = useState("");
useAsyncEffect(
function* () {
setText("fetching...");
const response = yield cpFetch(props.url);
const json = yield response.json();
setText(`Success: ${JSON.stringify(json)}`);
},
[props.url]
);
return <div>{text}</div>;
}
const api = {}
api.getAllPokemon = function*() => {
const respose= yield cpFetch('http://localhost:8080/pokemon', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
const pokemon= yield response.json();
return pokemon.rows.map(({ name }) => name));
};
export default API;
useAsyncEffect(function*(){
const names= yield* api.getAllPokemon(setResponse);
// changeState here
},[])