javascript - 在反应钩子中获取formData中的空值
问题描述
大家好,我在使用带有formData的react功能组件钩子时遇到了一些问题我在formData中获得了空数据我正在使用usestate钩子但我得到了balnk数组作为输出
const [profilestate, setProfileState] = useState({
dob:"",
city:"",
state:"",
country:"",
school: "",
board: "",
age: "",
gender: "",
degree_college: "",
masters_college: "",
organizations: "",
department: "",
title: "",
profile_image:""
});
const handleChange = (e) => {
setProfileState({
...profilestate,
[e.target.name]: e.target.value
});
}
const handleFileChange = (e) => {
setProfileState({
...profilestate,
profile_image: e.target.files[0]
})
}
const { dob, state, city, country, school, board, age, gender, degree_college, masters_college, organizations, department, title, profile_image } = profilestate;
const formdata = new FormData();
formdata.append('dob', dob);
formdata.append('city', city);
formdata.append('state', state);
formdata.append('country', country);
formdata.append('school', school);
formdata.append('board', board);
formdata.append('age', age);
formdata.append('gender', gender);
formdata.append('degree_college', degree_college);
formdata.append('masters_college', masters_college);
formdata.append('organizations', organizations);
formdata.append('department', department);
formdata.append('title', title);
formdata.append('profile_image', profile_image);
const response = await fetch(Constants.url + 'auth/addUserDetail', {
method: 'POST',
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${JSON.parse(localStorage.getItem('token'))}`
},
body: formdata
});
const result = await response.json();
if (result.status === 'success') {
hideLoader()
toast.success(result.message);
}
else {
hideLoader()
toast.error(result.message);
return false;
}
任何人都可以帮助我,我将数据作为空数组获取我在钩子中使用 formData 任何帮助将不胜感激。
解决方案
const addUser= async ()=>{
const api_url = Constants.url + 'auth/addUserDetail';
const config = {
headers: {
contentType: 'application/json',
'Authorization': `Bearer ${JSON.parse(localStorage.getItem('token'))}`
}
}
const response = await axios.post(url, {...profilestate},config);
console.log(response.data); //get the response
/* do rest of stuff */
}
根本不需要使用表单数据。Api 只期望您可以通过axios轻松发送的对象形式的表单主体。您已经拥有包含所有数据的本地状态对象。我希望上面的想法能帮助你弄清楚并简化问题。
推荐阅读
- c - 如何为用户输入的候选者数量创建一个变量
- excel - 使用新的 Excel 排序功能。仅返回匹配结果的数组
- css - 如何在 React 中的按钮下制作图像框
- laravel - Laravel尝试访问null类型值的数组偏移量
- sql - 如何动态更改sql查询以添加周数?
- python - 如何在python中反转多索引数据透视表
- html - 为什么我不能使用“背景图像”属性放置背景图像?
- javascript - 如何从 if-else 语句中调用函数?
- mysql - Mysql索引表的列
- jupyter-notebook - 如何使用 if 和 else 选项在 Markdown 中编写函数