reactjs - 可以直接从 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}
</>
}
解决方案
推荐阅读
- mysql - 如何在没有 FROM_UNIXTIME() 函数的情况下将 unix 时间转换为 GMT+8 人类可读日期?
- c# - 如何使用单个 Selenium c# Webdriver/ChromeDriver 在两个选项卡中打开 2 个不同的链接?
- audiokit - 在 AudioKit v5 中使用音序器控制振荡器
- google-cloud-platform - 在 Pulumi 中,定义 GCP CloudBuild 触发器时,我将什么用作托管密钥的 kmsKeyName?
- mysql - 为每个传感器选择最近的测量值
- r - 如何使用 dplyr 获得相同的分组结果以获得与 sqldf 结果一致的结果?
- python - 没有名为“signxml”的模块
- reactjs - Recharts Js如何始终从响应容器底部渲染区域图
- r - R中的ggplot2包问题,如何设置颜色和图例
- django - 在 Django 连接中使用指定的数据库