我有一個帶有一些輸入的表單,帶有默認值并且它是隱藏的。我想使用 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;
uj5u.com熱心網友回復:
我認為您的問題可能是由于您將 post_id 的初始狀態設定為空字串,據我所知,它永遠不會更新。
我認為您甚至不需要將 post_id 保持在 commentInput 狀態。只需將其洗掉并將您的資料物件更改為:
const data = {
post_id: post.post_id,
commentcontent: commentInput.commentcontent,
};
uj5u.com熱心網友回復:
在您的內部,您submitComment可以使用:
const postId = e.target["postId"].value
如果您將以下內容添加到隱藏的輸入中:
name="postId"
但是在您的實體中,您可以只使用post.postid從道具中獲取的資訊,而不是從隱藏的輸入中獲取資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/528986.html
標籤:javascript反应
下一篇:如何遍歷結構化的正則運算式搜索?
