我做了一个小的Web应用程序,我希望用户能够登录时,他们填写的表格和更改页面。当表单提交时,我希望我的代码检查输入的数据是否正确,然后发送用户到不同的页面。我怎么能做到这一点,每次我这样做,我只是得到错误说,我不能把钩在那里。我甚至试过把钩子放在一个单独的函数中,如果满足条件,就调用这个函数,但仍然不起作用
所以我的问题是为什么它们不能是条件,比如为什么我可以把它们放在if语句中,以及我如何能够修复我的代码,以便我可以根据if语句的结果导航和更改页面。
编码
AccountSlice.tsx
const tologin = () => {
const Navigate = useNavigate();
Navigate('/Home')
}
const AccountSlice = createSlice({
name: "Account",
initialState: {ActiveAccount: [], Accounts: [{id: 1, email: "Member@mail.com", password: "password", isActive:false, roles: "Member"},{id: 2, email: "Manager@mail.com", password: "password", isActive:false, roles: "Manager"}]},
reducers: {
LoginFunc : (state, action) => {
let account= state.Accounts.find((account:any)=> account.email == action.payload.email && account.password == action.payload.password)
if(account != null){
console.log("logged in")
state.ActiveAccount.pop()
state.ActiveAccount.push(account)
tologin()
}
else{
}
},
LogOut : (state, Action) => {
console.log("Logged Out")
}
}
})
export default AccountSlice.reducer;
export const { LoginFunc, LogOut} = AccountSlice.actions;
登录组件
const Login = ({onSubmit}) => {
const [Email, setEmail] = useState("")
const [Password, setPassword] = useState("")
const handleSubmit = e => {
e.preventDefault()
onSubmit(Email, Password)
}
return(
<>
<div className="Login">
<div className='Login-form'>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="firstName">First Name</label>
<input type="text" value={Email} onChange={e => setEmail(e.target.value)}/>
</div>
<div>
<label htmlFor="Password">Password</label>
<input type="password" value={Password} onChange={e => setPassword(e.target.value)}/>
</div>
<br />
<button className='form-control' type="submit">Submit</button>
</form>
</div>
</div>
</>
)
}
const mapDispatchToProps = (dispatch) => {
return{
onSubmit: (Email, Password) => {
dispatch(LoginFunc({email:Email, password:Password }));
},
};
};
export default connect(mapDispatchToProps)(Login)
1条答案
按热度按时间gblwokeq1#
状态更改触发重新渲染,但您不能渲染函数,除非它们是 * 组件 *。所以钩子只能在组件内部使用,因为它们封装了状态。不要在外部定义函数,而是将其放在Login组件中并进行相应的导航。您可以用另一个组件 Package 您的组件,该组件将根据状态更改自动导航用户。