我尝试在我的模块中实现我的自定义钩子。但这表明我违反了一些钩子规则
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自定义钩子中进行任何修改,请建议我
发布于 2020-05-19 11:00:23
您正试图在MedicineContainer外部调用
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;
https://stackoverflow.com/questions/61889294
复制相似问题