【发布时间】:2020-12-16 13:41:44
【问题描述】:
我有一个句柄更改功能,它应该将照片、标题和文本上传到 formData
const handleChange = (name) => (event) => {
const value = name === "photo" ? event.target.files[0] : event.target.value;
this.postData.set(name, value);
console.log(this.postData);
};
这是我尝试上传照片的 JSX(文本和标题有类似的输入标签)
<div className="flex flex-wrap mb-6">
<div className="relative w-full appearance-none label-floating">
<input
className="tracking-wide py-2 px-4 mb-3 leading-relaxed appearance-none block w-full bg-gray-200 border border-gray-200 rounded focus:outline-none focus:bg-white focus:border-gray-500"
id="photo"
type="file"
accept="image/*"
value={state.photo}
onChange={handleChange("photo")}
/>
<label
for="name"
className="absolute tracking-wide py-2 px-4 mb-4 opacity-0 leading-tight block top-0 left-0 cursor-text"
>
Photo
</label>
</div>
</div>
postData 我正在尝试在 useEffect 挂钩中启动
useEffect(() => {
this.postData = new FormData();
});
然后在单击按钮时,我调用我的 createPost(),它对我的后端进行 axios 调用以使用我的 formData 创建一个帖子
const createPost = (postData) => {
// console.log("user ID from route params", props.match.params.userId);
const userId = props.match.params.userId;
const token = isAuthenticated().token;
const config = {
headers: { Authorization: `Bearer ${token}` },
};
const bodyParameters = {
key: "value",
};
const body = postData;
axios
.post(
`http://localhost:8000/post/new/${userId}`,
bodyParameters,
config,
body
)
.then(function (response) {
if (response.status === 200) {
setState((prevState) => ({
...prevState,
title: response.data,
}));
console.log(response.data);
} else {
console.log("Some error ocurred");
setState((prevState) => ({
...prevState,
redirect: true,
}));
}
})
.catch(function (error) {
console.log(error);
});
};
它不起作用我错过了什么?
【问题讨论】:
-
什么是“this.postData”?
-
嗨,罗伊,感谢您的回复。好吧,我正在尝试将 postData 转换为 FormData 对象,我认为这里就像是在做一个 componentDidMount。我稍后用表单输入中的照片、标题和文本填充 postData
-
我觉得还是用 useState hook 比较好
-
我明白了。那么使用表单输入中的值更新状态,然后将它们添加到 FormData 中?那怎么做?那么如何将 FormData 传递给我的 CreatePost 函数?
标签: reactjs forms react-hooks form-data use-effect