我正在尝试将在 Formik 中创建的表单发送到 json-server,但我收到警告说我没有使用函数,但需要一个函数。并且发送不会发生。我不明白我到底做错了什么。
const HeroesAddForm = () => {
const request = useHttp()
const dispatch = useDispatch()
const onSubmitForm = (values) => {
const newHero = {id: uuidv4(), ...values}
request(`http://localhost:3001/heroes`, 'POST', JSON.stringify(newHero))
.then(res => console.log(res, 'Отправка успешна'))
.then((res) => dispatch(heroCreate(res)))
.catch(err => console.log(err))
}
return (
<Formik
initialValues = {{
name: '',
description: '',
element: ''
}}
onSubmit = {(values) => onSubmitForm(values)}>
<Form className="border p-4 shadow-lg rounded">
<div className="mb-3">
<MyTextInput
label="Имя нового героя"
required
type="text"
name="name"
className="form-control"
id="name"
placeholder="Как меня зовут?"/>
</div>
<div className="mb-3">
<label htmlFor="description" className="form-label fs-4">Описание</label>
<Field
as="textarea"
required
name="description"
className="form-control"
id="description"
type="text"
placeholder="Что я умею?"
style={{"height": '130px'}}/>
</div>
<div className="mb-3">
<label htmlFor="element" className="form-label">Выбрать элемент героя</label>
<Field
required
className="form-select"
id="element"
name="element"
as="select">
<option >Я владею элементом...</option>
<option value="fire">Огонь</option>
<option value="water">Вода</option>
<option value="wind">Ветер</option>
<option value="earth">Земля</option>
</Field>
</div>
<button type="submit" className="btn btn-primary">Создать</button>
</Form>
</Formik>
)
}
使用http:
import { useCallback } from "react";
export const useHttp = () => {
const request = useCallback(async (url, method = 'GET', body = null, headers = {'Content-Type': 'application/json'}) => {
try {
const response = await fetch(url, {method, body, headers});
if (!response.ok) {
throw new Error(`Could not fetch ${url}, status: ${response.status}`);
}
const data = await response.json();
return data;
} catch(e) {
throw e;
}
}, []);
return {request}
}

您调用不正确,您现在有一个请求对象,请执行以下操作: