简体   繁体   English

如何在同一个组件中多次使用自定义组件

[英]How to use custom component multiple times in same component

Basically i've created one custom component for api calling基本上我已经为 api 调用创建了一个自定义组件

import React, {useState, useEffect} from 'react';
import axios from 'axios';

export const useFetch = config => {
  const [Response, setResponse] = useState({});
  const [Error, setError] = useState({});
  const [ShowModal, setShowModal] = useState(false);
  const [ShowLoader, setShowLoader] = useState(false);

  useEffect(() => {
    callAPI();
  }, []);

  const callAPI = () => {
    setShowLoader(true);
    axios(config)
      .then(res => {
        console.log('==>>', res);
        if (res.status == 200) {
          setShowLoader(false);
          setResponse(res.data);
        }
      })
      .catch(err => {
        console.log('==>>', err.response);
        setError(err.response.data);
        setShowLoader(false);
        setShowModalErrorMessage(err.response.data.error);
        setShowModal(true);
      });
  };

  return {Response, Error, ShowModal, ShowLoader};
};

with the help on this i can call api and get response if i use it with useEffect/componentDidMount in component.在这方面的帮助下,我可以调用 api 并在我将它与组件中的 useEffect/componentDidMount 一起使用时获得响应。 But how to use same for calling different api on Button click.但是如何在单击按钮时使用相同的方法调用不同的 api。 is it possible?可能吗?

i followed this=>post我关注了这个=>帖子

Add setUrl method (can expand to setConfig) in useFetch .useFetch中添加setUrl方法(可以扩展为 setConfig)。 Here working demo for this in stackblitz这里是stackblitz中的工作演示

import React, {useState, useEffect} from 'react';
import axios from 'axios';

const useFetch = ({}) => {
  const [Response, setResponse] = useState({});
  const [Error, setError] = useState({});
  const [ShowModal, setShowModal] = useState(false);
  const [ShowLoader, setShowLoader] = useState(false);
  const [url, setUrl] = useState("");

  useEffect(() => {
    if (url) {
      console.log('making request ', url);
      callAPI();
    }
  }, [url]);

  const callAPI = () => {
    setShowLoader(true);
    axios(url)
      .then(res => {
        console.log('==>>', res);
        if (res.status == 200) {
          setShowLoader(false);
          setResponse(res.data);
        }
      })
      .catch(err => {
        console.log('==>>', err.response);
        setError(err.response.data);
        setShowLoader(false);
        setShowModalErrorMessage(err.response.data.error);
        setShowModal(true);
      });
  };

  return {Response, Error, ShowModal, ShowLoader, setUrl};
};

export default useFetch;

On the button click, set url (expand to config)在按钮上单击,设置 url(展开到配置)

import React, {useState, useEffect} from 'react';
import useFetch from './use-fetch';

export default ({ name }) => {
  const {Response, Error, ShowModal, ShowLoader, setUrl } = useFetch({});


 return (<div>
  <button key={'1'} onClick={() => setUrl("http://foo/items")}> Request 1 </button>
  <button key={'2'} onClick={() => setUrl("http://foo/other")}> Request 2 </button>
 </div>)

};

Common Request.js file using the fetch method使用 fetch 方法的通用 Request.js 文件

Request("POST","http://localhost/users/user",{'name':"",'add':""})请求("POST","http://localhost/users/user",{'name':"",'add':""})

export default function Request(reqMethod, endPointUrl, bodyData) {   
 if (reqMethod === "POST") {
     return fetch(endPointUrl, {
        method: reqMethod,
        body: JSON.stringify(bodyData),
      })
  .then((response) => {
    return response.json();
  })
  .catch(() => {
    localStorage.clear();
  });
 } else if (reqMethod === "GET") {
    return fetch(endPointUrl, {
    method: reqMethod,
    })
  .then((response) => {
    return response.json();
  }).catch(() => {
    localStorage.clear();
  });
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM