React.js useReducer钩子错误ReferenceError:初始化前无法访问'reducer'

时间:2020-03-01 16:04:23

标签: reactjs react-hooks

我正在通过阅读在线教程来学习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]);

请让我知道如何改进此代码,以及为什么会出现此错误?

1 个答案:

答案 0 :(得分:2)

正如Asyush在评论部分中指出的那样,并对其进行解构以使其更整洁,尽管我建议将reducer放在单独的文件中,但其余的看起来不错

      function ProfileForm(props) {
    const form = useForm();
    const {
      register,
      handleSubmit,
      errors,
      formState: { isSubmitting }
    } = form;

    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;          
        }  
    }
// Change the name to avoid conflict because of destructure
   const [profileReducer, dispatch] = useReducer(reducer, profileInitSate)    

   let {profile} = props.location.state;

   let {displayName,realName,birthDate,height}=profile;

    useEffect(() => {
      if(props.location.state.profile){
          dispatch({type: 'dispalyName', 
          value: displayName})
          dispatch({type: 'realName', 
          value: realName})
          dispatch({type: 'birthDate', 
          value: birthDate})
          dispatch({type: 'height', 
          value: height})
       }

      }, [profileReducer]);