【发布时间】:2021-12-24 12:41:27
【问题描述】:
如何在上面的代码中添加fetch 我试图在 setEffect 中使用 fetch 调用 rest API,但出现错误。
目标:在我提交表单时调用其余 API。 到目前为止,我能够从表单动态生成 URL,并且无法连接以获取和调用其余 API。
const { useState } = React;
function Example() {
const [ form, setForm ] = useState({});
function handleSubmit() {
const uri = `http://example.com/?${form.one}&${form.two}`;
console.log(`Current state: ${JSON.stringify(form)}`);
console.log(`Fetch URI: ${uri}`);
// fetch(uri)... etc
}
function handleChange(e) {
const { nodeName, name, value } = e.target;
if (nodeName === 'INPUT') {
setForm({ ...form, [name]: value });
}
}
return (
<form onChange={handleChange}>
<fieldset>
<legend>Input one</legend>
<input name="one" value={form.one} />
</fieldset>
<fieldset>
<legend>Input two</legend>
<input name="two" value={form.two} />
</fieldset>
<button type="button" onClick={handleSubmit}>Submit</button>
</form>
);
};
ReactDOM.render(
<Example />,
document.getElementById('react')
);
【问题讨论】:
-
首先,
onChange应该在输入元素上,而不是在表单上。你应该制作按钮type="submit"。您应该在表格中添加onSubmit={handleSubmit}。在handleSubmit内,您应该添加事件并防止默认行为handleSubmit(e) { e.preventDefault(); ... }。既然已经不碍事了,你有没有查过如何做一个获取请求?您是否查看过如何从该获取请求中设置状态值?
标签: reactjs rest react-hooks fetch flask-restful