如何实现自定义获取挂钩

时间:2020-05-19 10:53:58

标签: javascript reactjs redux react-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自定义挂钩中进行任何修改

1 个答案:

答案 0 :(得分:0)

  • 您正试图在MedicineContainer之外调用useFetch
const res = useFetch('http://localhost:5000/api/medicines', {});
console.log(res, 'popopo');
  • 您在MedicineContainer中使用useFetch不正确。您需要使用url和options调用它,并使用返回的值而不是再次保持状态
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;