0

我想创建一个包含 useReducer 钩子作为单例的高阶函数,以便与其他组件复合。但我得到一个错误:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

我的霍夫:

const initialState = {
  status: ''
};

const reducer = (state = initialState, action) => {
  switch(action.type) {
    case 'SHOW':
      return {
        ...state
      }
    default:
      return state;
  }
}

const WithReducer = WrappedComponent => (props) => {
  const [state, dispatch] = useReducer(reducer, initialState)
  return (
    <>
      <WrappedComponent {...props}/>
    </>
  )
}

export default WithReducer;

并尝试撰写:

connect(mapStateToProps, mapDispatchToProps)(WithReducer(App));

我哪里做错了 ?

4

1 回答 1

1

得到了自己的答案

 const WithReducer = WrappedComponent => {
      const Reducer = (props) => {
        const [state, dispatch] = useReducer(reducer, initialState);
        return (
          <>
            <div>{state.status}</div>
            <WrappedComponent {...props} state={state} dispatch={dispatch}/>
          </>
        )
      }
      return Reducer;
    }
于 2020-10-16T09:35:56.940 回答