[英]React useEffect async warning?
我試圖擺脫 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)
}, [])
你不能結合 await 和 promise
並且 useEffect 中的 async 也有一點不同。
當你異步你的 fetch .then 不起作用,但它會為你返回響應
所以我們需要寫 try 和 catch
useEffect(() => {
try {
const fetchData = async () => {
const res = await fetch("http://localhost:8080/pokemon");
setBaseExperience(res);
};
fetchData();
} catch (err) {
console.log(err);
}
}, []);
使用提取包裝器的 JSON 提取示例( 現場演示)
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
},[])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.