表单提交时调用React自定义挂钩



我创建了一个自定义的useFetch钩子,以便在应用程序的几个不同区域发出API请求。它正在使用的一个实例是在渲染组件时,因此它可以按预期工作。然而,当用户提交表单时,我有另一个地方要提出请求;应为赋值或函数调用,而看到的却是表达式";在显示handleSubmit 内{data}的行

App.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>
))}
);
}

useFetch.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
};

如果你需要再次触发你的钩子,你可以更改数据或添加一个触发函数,在你的钩子中:

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};