我有一个输入,用户应该有姓氏,如果输入值包括空格(' ')
,我将使用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>
只需使用nameState.nameValue = "";
并删除dispatchNameState
即可清除输入。
//Form Submit Handler
const addUserHandler = (e) => {
e.preventDefault();
nameState.nameValue = "";
};
从useReducer 中删除此代码
if(action.type === 'CLEAR'){
return{
userName: '',
}
}