簡體   English   中英

在表單提交上調用 React 自定義鈎子

[英]Invoke React custom hook on form submit

我創建了一個自定義 useFetch 掛鈎,以便在應用程序的幾個不同區域發出 API 請求。 它正在使用的一個實例是在渲染組件時,因此它按預期工作。 但是,當用戶提交表單時,我還有另一個地方要發出請求。 我在句柄提交中顯示 {data} 的行處遇到錯誤,指出“預期分配或 function 調用,而是看到一個表達式”

應用程序.js:

import { useFetch } from "./components/useFetch";

function App() {
  const [value, setValue] = useState([]);
  const {data} = useFetch("search", value);

  const handleChange = event => {
    setValue(event.target.value);
  };

  const handleSubmit = event => {
    event.preventDefault();
    setData("search", value);
  };

  return (
    <Form onSubmit={handleSubmit}>
       <Form.Group>
           <InputGroup className="mb-3">
               <FormControl value={value} onChange={handleChange} placeholder="Search" aria-label="Search" aria-describedby="basic-addon2" />
                  <InputGroup.Append>
                    <Button type="submit" variant="primary">Search</Button>
                  </InputGroup.Append>
                </InputGroup>
              </Form.Group>
            </Form>
    {data.map(data => (
      <p>{data.description}</p>
    ))}
  );
}

使用Fetch.js:

import { useState, useEffect } from 'react';

export const useFetch = (endpoint, value) => {

  const [isLoaded, setIsLoaded] = useState(false);
  const [error, setError] = useState(null);
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(`http://127.0.0.1:8443/${endpoint}/${value}/?key=key`, {
        mode: 'cors',
        credentials: 'include'
      })
        .then(res => res.json())
        .then(
          (json) => {
            setIsLoaded(true);
            setData(json.result);
          },
          (error) => {
            setIsLoaded(true);
            setError(error);
          }
        )
    };
    fetchData();
  }, [endpoint, value]);

  return {data};

};

出色地

 const handleSubmit = event => {
    event.preventDefault();
    {data} //this is not a function call this is an obj definition without assignement so is just an error
  };

如果您需要再次觸發您的鈎子,您可以更改數據或添加觸發器 function 所以,在您的鈎子中:

const doStuff =   async () => {
  const response = await fetch(`http://127.0.0.1:8443/${endpoint}/${value}/?key=key`, {
    mode: 'cors',
    credentials: 'include'
  })
    .then(res => res.json())
    .then(
      (json) => {
        setIsLoaded(true);
        setData(json.result);
      },
      (error) => {
        setIsLoaded(true);
        setError(error);
      }
    )
};
}


 useEffect(doStuff, [endpoint, value]);


  return {data, doStuff};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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