首页 > 解决方案 > 在反应钩子中获取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 任何帮助将不胜感激。

标签: javascriptreactjs

解决方案


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轻松发送的对象形式的表单主体。您已经拥有包含所有数据的本地状态对象。我希望上面的想法能帮助你弄清楚并简化问题。


推荐阅读