事情很简单,很清楚,我想在提交字段时清除输入字段。
状态:
const [formData, setFormData] = useState({
linkName: "",
link: ""
});
handleSubmit
功能:
Axios.post("/api/social", body, config)
.then(
setSocialList(prev => [
...prev,
{ _id: Math.random(), link, linkName }
])
)
.then(setFormData({ link: " ", linkName: " " }));
} catch (err) {
console.error(err);
}
因此,我无法清除自己的formData
状态,因此提交时输入字段不会清除。
答案 0 :(得分:1)
您需要在此处进行双向绑定。将.then(setFormData({ link: " ", linkName: " " }))
作为值传递给您的linkName
。
input
此外,正如 @norbitrial 所建议的那样,您需要将回调传递给上一个<Input
type="text"
name="linkName"
placeholder="Ex. Facebook"
onChange={e => onChange(e)}
value={linkName}
/>
呼叫,如下所示:
.then()
注意::我已从上述重新分配中删除了单个字符的空格。
也可以在其他.then(() => { setFormData({ link: "", linkName: "" } }));
中执行相同的操作。
答案 1 :(得分:1)
您需要将link和linkName的值与输入字段绑定,否则该值将在状态中更新,但输入仍将具有输入的值,并且不会反映任何以编程方式更新的值。
import React, { Fragment, useState, useContext } from "react";
import { Button, Form, FormGroup, Label, Input, Row, Col } from "reactstrap";
import Axios from "axios";
import { SocialContext } from "./SocialContext";
const SocialForm = () => {
const [formData, setFormData] = useState({
linkName: "",
link: ""
});
const [socialList, setSocialList] = useContext(SocialContext);
const { linkName, link } = formData;
const onChange = e =>
setFormData({ ...formData, [e.target.name]: e.target.value });
const token = localStorage.getItem("token");
const handleSubmit = e => {
e.preventDefault();
const socialList = {
linkName,
link
};
try {
const config = {
headers: {
"Content-Type": "application/json",
"x-auth-token": `${token}`
}
};
const body = JSON.stringify(socialList);
Axios.post("/api/social", body, config)
.then(
setSocialList(prev => [
...prev,
{ _id: Math.random(), link, linkName }
])
)
.then(setFormData({ link: " ", linkName: " " }));
} catch (err) {
console.error(err);
}
};
return (
<Fragment>
<br />
<Form onSubmit={e => handleSubmit(e)} className="socialForm">
<Row form>
<Col md={5}>
<FormGroup>
<Label for="LinkName">LinkName</Label>
<Input
type="text"
name="linkName"
value={linkName}
placeholder="Ex. Facebook"
onChange={e => onChange(e)}
/>
</FormGroup>
</Col>
<Col md={5}>
<FormGroup>
<Label for="Link">Link</Label>
<Input
type="text"
name="link"
value={link}
placeholder="Ex. https://www.facebook.com/"
onChange={e => onChange(e)}
/>
</FormGroup>
</Col>
</Row>
<Button>Add</Button>
</Form>
</Fragment>
);
};
export default SocialForm;
答案 2 :(得分:0)
该问题基本上是setFormData
函数被立即调用,因此您没有在then
帖子后的之后传递要调用的回调。完成。
基于此,您需要:
Axios
代替:
.then(() => setFormData({ link: " ", linkName: " " }))
我希望这会有所帮助!