[英]How to implement custom fetch hooks
我嘗試在我的模塊中實現我的自定義鈎子。 但它表明我違反了一些鈎子規則
import React, { useState, useEffect } from 'react';
import useFetch from '../../Helpers/Custom useFetch()';
import MedicineList from './MedicineUI';
const MedicineContainer = () => {
const [medicineLists, setMedicineList] = useState([]);
useEffect(() => {
fetch('http://localhost:5000/api/medicines')
.then((response) => response.json())
.then((medicineList) => {
setMedicineList(medicineList);
});
}, []);
return <MedicineList medicineList={medicineLists} />;
};
const res = useFetch('http://localhost:5000/api/medicines', {});
export default MedicineContainer;
自定義獲取代碼如下
import React, { useEffect, useState } from 'react';
const useFetch = (url, options) => {
const [response, setResponse] = React.useState(null);
const [error, setError] = React.useState(null);
const [isLoading, setIsLoading] = React.useState(false);
React.useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
try {
const res = await fetch(url, options);
const json = await res.json();
setResponse(json);
setIsLoading(false);
} catch (error) {
setError(error);
}
};
fetchData();
}, [options, url]);
return { response, error, isLoading };
};
export default useFetch;
如果 useFetch 自定義鈎子需要任何修改,建議我
const res = useFetch('http://localhost:5000/api/medicines', {});
console.log(res, 'popopo');
import React, { useState, useEffect } from 'react';
import useFetch from '../../Helpers/Custom useFetch()';
import MedicineList from './MedicineUI';
const MedicineContainer = ( ) => {
const { response, error, loading } = useFetch('http://localhost:5000/api/medicines', { } );
if ( loading ) {
return <div>Loading...</div>
}
return <MedicineList medicineList={response} />;
};
export default MedicineContainer;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.