【发布时间】:2022-09-27 18:31:00
【问题描述】:
我有一个用户应该有姓氏的输入,如果输入值包含空格(\' \') 并存储该值,我将使用useReducer() 挂钩进行验证。一切正常我也正确收到了无效消息。
但是在提交表单后我想清除输入值,我在useReducer 操作逻辑中尝试过,但它不起作用。
这是我的代码:-
const [nameState, dispatchNameState] = useReducer(
(state, action) => {
if (action.type === \"USERNAME\") {
return {
userName: action.nameValue,
isValid: action.nameValue.includes(\" \"),
};
}
if(action.type === \'USER_ON_CHANGE\'){
return{
userName: state.userName,
}
}
if(action.type === \'CLEAR\'){
return{
userName: \'\',
}
}
},
{
userName: \"\",
isValid: null,
}
);
//Form Submit Handler
const addUserHandler = (e) => {
e.preventDefault();
const userData = {
userName: nameState.userName,
};
//Data transfer with props
addedUser(userData);
dispatchNameState({
type: \'CLEAR\',
})
};
///JSX
<div className=\"form__group\">
<input
type=\"text\"
placeholder=\"Full Name\"
value={nameState.nameValue}
onChange={(e) =>
dispatchNameState({
type: \"USER_ON_CHANGE\",
nameValue: e.target.value,
})
}
onBlur={(e) =>
dispatchNameState({
type: \"USERNAME\",
nameValue: e.target.value,
})
}
/>
{nameState.isValid === false && (
<span className=\"invalid\">*Enter your full name</span>
)}
</div>
标签: reactjs forms validation react-hooks use-reducer