我有一個名為“useFetch”的自定義鉤子,它發出一個 AJAX 請求并將結果存盤在狀態中。我只是想使用組件中的函式格式化從 ajax 接收到的資料,但不確定如何執行此操作,因為僅在接收到資料后才需要呼叫該函式。
一個例子如下:
import React, { Component, useState } from "react";
import useFetch from "../../../Hooks/useFetch";
const Main = () => {
const { data, isPending, error } = useFetch(
"http://127.0.0.1:8000/api/historic/1"
);
function formatData(data){
//Do some processing of the data after it's been received
}
//This doesn't work of course because it runs before the data has been received
const formatted_data=formatData(data);
return (
//Some display using the formatted data
);
};
export default Main;
這是上面組件中使用的自定義鉤子useFetch。我寧愿不必在此處進行格式化,因為格式化與上述組件特別相關,并且此自定義掛鉤旨在具有更通用的實用性。
import { useState, useEffect } from "react";
const useFetch = (url) => {
const [data, setData] = useState(null);
const [isPending, setisPending] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortCont = new AbortController();
fetch(url, { signal: abortCont.signal })
.then((res) => {
if (res.ok) {
return res.json();
} else {
throw Error("could not fetch data for that resource");
}
})
.then((data) => {
setData(data);
setisPending(false);
setError(null);
})
.catch((er) => {
if (er.name === "AbortError") {
console.log("fetch aborted");
} else {
setError(er.message);
setisPending(false);
}
});
return () => abortCont.abort();
}, [url]);
return { data, isPending, error };
};
export default useFetch;
uj5u.com熱心網友回復:
您應該使用帶有資料的 useEffect 鉤子包裝它,因為它是 deps。
const [formattedData, setFormattedData] = useState();
useEffect(() => {
if (!data) return;
const _formattedData = formatData(data);
setFormattedData(_formattedData);
}, [data]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/399033.html
標籤:反应
