我有一个带有默认值和隐藏值的输入表单。我想提交它的值,连同其他输入到数据库使用API,我已经尝试了以下方法,但它不工作。请帮助。
const PostWidget = ({ post }) => {
const [loading, setLoading] = useState(false);
const [show, setShow] = useState(false);
const [commentInput, setComment] = useState({
post_id: '',
commentcontent: '',
});
const [errorlist, setError] = useState([]);
const handleInput = (e) => {
e.persist();
setComment({ ...commentInput, [e.target.name]: e.target.value });
}
const submitComment = (e) => {
e.preventDefault();
setLoading(true);
const data = {
post_id: commentInput.post_id,
commentcontent: commentInput.commentcontent,
};
axios.post(`/api/store-comment`, data).then((res) => {
if (res.data.status === 200) {
toast.success(res.data.message, "success");
setLoading(false);
}
else if (res.data.status === 422) {
toast.error("Your Comment is too Long", "", "error");
setError(res.data.errors);
setLoading(false);
}
});
}
return (
<div className="form-group boxed">
<div className="input-wrapper">
<form onSubmit={submitComment}>
<input defaultValue={post.postid} hidden />
<input type="text" name="commentcontent" className="form-control" onChange={handleInput} value={commentInput.commentcontent} placeholder="Write your Comment" />
<button type="submit" className="send-input">
{loading ? <><span className="spinner-border spinner-border-sm spinner-comment" role="status" aria-hidden="true"></span></> : <><i className="fi fi-rr-arrow-circle-right"></i></>}
</button>
</form>
</div>
);
}
export default PostWidget;
我认为你的问题可能是由于你设置的初始状态的post_id为空字符串,据我所知,它永远不会得到更新。
我不认为你甚至需要保持post_id在commentInput状态。只需删除它并将数据对象更改为:
const data = {
post_id: post.post_id,
commentcontent: commentInput.commentcontent,
};
在您的submitComment
内部,您可以使用:
const postId = e.target["postId"].value
如果你添加以下隐藏输入:
name="postId"
但是在你的例子中,你可以使用从道具中获取的post.postid
,而不是从隐藏输入中获取。