首页 > 解决方案 > 可以直接从 useReducer 返回一个组件吗?

问题描述

我可以使用 useReducer 将组件作为复杂状态返回吗?

useReducer 始终用于将数据对象作为状态来管理,一旦状态改变,组件将重新渲染。从 useReducer 返回组件的好处是我们可以将所有逻辑放在 reducer 函数中,无需根据状态逻辑更改特定的渲染。

我不想写这样的代码:


() => {
  const [state, dispatch] = useReducer((prevState, action) => {
    const {type, payload} = action;
    switch(type) {
      case 'loaded':
        return {...prevState, isLoading: false};
      case 'loading':
        return {...prevState, isLoading: true};
      default:
        return prevState;
    }
  }, {isLoading: true});

  return <>
           {state.isLoading && <Loading />}
           {!state.isLoading && <DoSomething />}
         </>
}

我可不可以做:


() => {
  const [state, dispatch] = useReducer((prevState, action) => {
    const {type, payload} = action;
    switch(type) {
      case 'loaded':
        return <DoSomething />;
      case 'loading':
        return <Loading />;
      default:
        return null;
    }
  }, {isLoading: true});

  return <>
           {state}
         </>
} 

标签: reactjsreact-hooks

解决方案


推荐阅读