我正在創建一個簡單的登錄頁面,但是email, password當用戶正確輸入他們的登錄資訊時,我無法讓這兩個輸入再次變為空白。他們正在正確重置所有其他狀態,除了這兩個setEmail(""),setPassword("")。
我正在使用 MUI 庫。
const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [errEmail, setErrEmail] = useState("");
const [errPassword, setErrPassword] = useState("");
const [checkErrEmail, setCheckErrEmail] = useState(false);
const [checkErrPassword, setCheckErrPassword] = useState(false);
const handleClickShowPassword = () => {
setShowPassword(!showPassword);
}
const onSubmitLogin = (event) => {
event.preventDefault();
const userLogin = {
email,
password
}
loginApi(userLogin)
}
const loginApi = async(body) => {
await axios.post(`${BASE_URL}/login`, body)
.then((res)=>{
console.log(res.data);
setEmail("")
setPassword("")
setErrEmail("");
setErrPassword("");
setCheckErrEmail(false);
setCheckErrPassword(false);
})
.catch((err)=>{
if(err.response.data.message.includes('Senha incorreta')){
setErrPassword(err.response.data.message);
setCheckErrPassword(true);
}else{
setErrEmail(err.response.data.message)
setCheckErrEmail(true);
}
console.log(err.response.data.message);
})
}
這是我使用狀態的地方。
return(
<Main>
<p>Entrar</p>
<Form onSubmit={onSubmitLogin}>
<InputMaterial
error={checkErrEmail}
helperText={checkErrEmail ? errEmail : ''}
id="outlined-basic"
label="Email"
type={'email'}
variant="outlined"
placeholder={'Email'}
onChange={(event)=>setEmail(event.target.value)}
required
/>
<DivPassword>
<InputMaterial
error={checkErrPassword}
helperText={checkErrPassword ? errPassword : ''}
id="outlined-basic"
label="Password"
type={showPassword ? 'password' : 'text'}
variant="outlined"
placeholder={'Mínimo 6 caracteres'}
inputProps={{pattern:'.{6,}', title:'Mínimo 6 caracteres'}}
onChange={(event)=>setPassword(event.target.value)}
required
/>
<IconButton
aria-label="toggle password visibility"
onClick={handleClickShowPassword}
edge="end"
>
{ showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</DivPassword>
<ButtonStyled type='submit'>Entrar</ButtonStyled>
</Form>
</Main>
匯出默認登錄)
}
我嘗試將 setEmail 和 setPassword 作為空字串 ("") 呼叫到它們的原始狀態,但它不起作用。
uj5u.com熱心網友回復:
您正在嘗試實作受控組件,但沒有value屬性:
<InputMaterial
error={checkErrPassword}
helperText={checkErrPassword ? errPassword : ''}
id='outlined-basic'
label='Password'
type={showPassword ? 'password' : 'text'}
variant='outlined'
placeholder={'Mínimo 6 caracteres'}
inputProps={{ pattern: '.{6,}', title: 'Mínimo 6 caracteres' }}
value = {password} // <------- add this
onChange={(event) => setPassword(event.target.value)}
required
/>;
如果沒有value此處的屬性,輸入將保持其自身的狀態并且不會使用 React 狀態作為源,因此腳本中其他地方的狀態更改將不會反映在輸入中。
在我看來,受控和非受控組件是在 React 中實作表單時需要理解的重要概念。請參閱 React 關于受控和非受控組件的檔案,以更好地理解這一點。
希望這可以幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/534359.html
