Javascript 创建更高阶的函数,用于将useReducer组合并使用到另一个组件中,这给了我一个错误

Javascript 创建更高阶的函数,用于将useReducer组合并使用到另一个组件中,这给了我一个错误,javascript,reactjs,composition,higher-order-functions,use-reducer,Javascript,Reactjs,Composition,Higher Order Functions,Use Reducer,我想创建一个更高阶的函数,它将useReducer hook作为一个单例来包含,以便与其他组件组合。 但我有一个错误: 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) =&

我想创建一个更高阶的函数,它将useReducer hook作为一个单例来包含,以便与其他组件组合。 但我有一个错误:

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;

我哪里出错了?

我自己得到了答案

 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;
    }
constwithreducer=WrappedComponent=>{
const Reducer=(道具)=>{
const[state,dispatch]=useReducer(reducer,initialState);
返回(
{state.status}
)
}
回流减速机;
}

我可以问你为什么要尝试将一个组件包装到一个HOC中,而不是直接在需要它的组件中使用
useReducer
钩子?主要思想是我们可以通过connect函数连接到redux状态,而无需钻取道具,我想通过创建一个带有useReducer HOC的HOF并通过组合连接我的应用程序的不同部分来重复这一功能。但我的错误是useReducer创建了一个新的状态实例,通过使用我的自定义HOF组合组件,我将不会有一个单例状态,而是独立的实例。我想我应该对上下文和useReducer使用。
 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;
    }