【发布时间】:2020-03-01 16:04:23
【问题描述】:
我正在通过阅读在线教程来学习 Reactjs 钩子。这是我的代码。我确信它可以改进。我收到了这个错误:-
ReferenceError: 在初始化之前无法访问“reducer”
function ProfileForm(props) {
const form = useForm();
const {
register,
handleSubmit,
errors,
formState: { isSubmitting }
} = form;
const [profile, dispatch] = useReducer(reducer, profileInitSate)
const profileInitSate = {
displayName: '',
birthDate: '',
height: 0,
}
const reducer = (state, action) =>{
switch(action.type){
case 'displayName' :
return {...state, displayName: action.value};
case 'realName':
return {...state, realName: action.value};
case 'birthDate':
return {...state, birthDate: action.value};
default:
return state;
}
}
useEffect(() => {
if(props.location.state.profile){
dispatch({type: 'dispalyName',
value: props.location.state.profile.displayName})
dispatch({type: 'realName',
value: props.location.state.profile.realName})
dispatch({type: 'birthDate',
value: props.location.state.profile.birthDate})
dispatch({type: 'height',
value: props.location.state.profile.height})
}
}, [profile]);
请告诉我如何改进此代码以及为什么会出现此错误?
【问题讨论】:
-
在调用
useReducer之前移动const reducer的声明 -
profileInitSate相同
标签: reactjs react-hooks