代码之家  ›  专栏  ›  技术社区  ›  kinhs

为什么preventDefault()方法在react应用程序中不适用于我?

  •  0
  • kinhs  · 技术社区  · 5 年前

    我使用一个表单来捕获用户的输入。但一旦用户单击submit按钮,页面就会重新加载。我不想让它重新加载。这就是我决定使用preventDefault()方法的原因。 我怎样才能让它工作?

    const handleHeaderValueUpdate = async ( headerId, e) =>{
    e.preventDefault()
    console.log(headerId)
    
      setUpdating(true)
      const updatedHeaderValue = {
      username: user.username,
      websiteName,
      sitesubName,
      };
      if(file){                    //logic behind uploading image and the image name
        const data = new FormData();
        const filename = Date.now() + file.name;
        data.append("name", filename);
        data.append("file", file);
        updatedHeaderValue.headerImg = filename;
    
      
        try{
        await axios.post("/upload", data)//handles the uploading of the image
        //setUpdated(true)
        }catch(err){
            dispatch({type: "UPDATE_FAILURE"})
        }
        }
    
        try{
        
        await axios.put("/headervalue/" + headerId, updatedHeaderValue)  
         setUpdating(false);
         setTextUpdate(true)
         //setUpdated(true)
      
    
    
     }catch(err){
       console.log(err)
    }
    
    }
    

     <form onSubmit={()=>handleHeaderValueUpdate(headerId)} className="dashboard-form">
    
            <div className='dasboard-input-div'>
              <p className="dashboard-label">Website Name</p>
              {dashboardEditMode ? <input className="dashboard-input" type="text" placeholder={singleValues.websiteName} autoFocus
                 onChange={(e) => setWebsiteName(e.target.value)}
                 required
                /> : 
                <input className="dashboard-input" type="text" placeholder= {singleValues.websiteName} readOnly/>
              }
      </form>
    

    这是提交按钮

    {dashboardEditMode && <button className={updating ? "updateModeBTN-unclick updateModeBTN" : "updateModeBTN"} type="submit">Update</button>}
    
    1 回复  |  直到 5 年前
        1
  •  2
  •   Ahmet Emre Kilinc    5 年前

    问题是您没有将事件发送到 handleHeaderValueUpdate 作用您应该更改:

    <form onSubmit={()=>handleHeaderValueUpdate(headerId)}
    

    致:

    <form onSubmit={(e) => handleHeaderValueUpdate(headerId, e)}
    

    你可以看看 this sandbox