我尝试在模块中实现自定义钩子。但是它表明我违反了一些挂钩规则
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自定义挂钩中进行任何修改
答案 0 :(得分:0)
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;