簡體   English   中英

如何實現自定義提取鈎子

[英]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 自定義鈎子需要任何修改,建議我

  • 您正在嘗試在 MedicineContainer 之外調用 useFetch
const res = useFetch('http://localhost:5000/api/medicines', {});
console.log(res, 'popopo');
  • 您在 MedicineContainer 中對 useFetch 的使用不正確。 您需要使用 url 和選項調用它,並使用返回值而不是再次維護 state
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM