React 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) 
}, [])

u不能组合等待和承诺

而且async在useEffect中也有一些不同。

当你异步你的fetch.then不起作用,但它会为你的返回响应

所以我们需要写try-and-catch

useEffect(() => {
try {
const fetchData = async () => {
const res = await fetch("http://localhost:8080/pokemon");
setBaseExperience(res);
};
fetchData();
} catch (err) {
console.log(err);
}
}, []);

使用fetch wrapper的JSON提取示例(Live Demo(

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
},[])

相关内容

  • 没有找到相关文章

最新更新