i'm studying useReducer hook with simple Login UI.
In Login.js
const [passwordState, dispatchPassword] = useReducer(passwordReducer, {
value: "",
isValid: null,
});
first, passwordReducer function is below. however this code cannot change state.
const passwordReducer = (state, action) => {
switch (action.type) {
case "PASSWORD_INPUT":
return { value: action.val, isVaild: action.val.trim().length > 6 };
case "PASSWORD_ONBLUR":
return { value: state.value, isValid: state.value.trim().length > 6 };
default:
return { value: "", isValid: false };
}
}
second, below similar IF code.
const passwordReducer = (state, action) => {
if (action.type === "PASSWORD_INPUT") {
return { value: action.val, isValid: action.val.trim().length > 6 };
}
if (action.type === "PASSWORD_ONBLUR") {
return { value: state.value, isValid: state.value.trim().length > 6 };
}
return { value: "", isValid: false };
};
this code works well.
i don't know why first case cannot work, second case works well..
i attached codesandbox link below.
Please looking at Login.js I don't know the difference.. thank you.
you got typo in:
switch (action.type) {
case "PASSWORD_INPUT":
return { value: action.val, isVaild: action.val.trim().length > 6 };
isVaild:
should read isValid:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.