reactjs - 使用 react-redux translate 函数时,渲染的钩子比预期的要少
问题描述
Rendered fewer hooks than expected. This may be caused by an accidental early return statement.
我在使用以下代码时收到一条消息:
{headRows
// Filter table columns based on user selected input
.filter(item => displayedColumns.includes(item.id))
.map(row => (
<TableCell
key={row.id}
align={row.numeric ? "right" : "left"}
padding={row.disablePadding ? "none" : "default"}
sortDirection={orderBy === row.id ? order : false}
>
<TableSortLabel
active={orderBy === row.id}
direction={order}
onClick={createSortHandler(row.id)}
>
{useTranslation(row.label)}
</TableSortLabel>
</TableCell>
))}
我的翻译功能如下所示:
import { useSelector } from "react-redux";
export const useTranslations = () =>
useSelector(state => state.translations.data, []);
如果我将字符串传递给它,则翻译功能按预期工作。但是,如果我替换{useTranslation(row.label)}
为{row.label}
,我将不再收到错误消息。在我看来,我没有在循环、条件或嵌套函数中调用 Hooks,还是我错了?
解决方案
您有一个呈现单元格列表的组件。但是这里的每个单元格都由传递给map
. 所以,事实上,这里既有循环又有嵌套函数。
我建议您将回调提取到一个新组件并呈现它。在这种情况下,每个单元格都将是一个新组件,允许您自由使用钩子。
const MyTableCell = props => {
const {row} = props;
const title = useTranslation(row.label);
return (
<TableCell>
<TableSortLabel>
{title}
</TableSortLabel>
</TableCell>
)
}
// and then
{headRows
// Filter table columns based on user selected input
.filter(item => displayedColumns.includes(item.id))
.map(row => (
<MyTableCell row={row} key={row.id} />
))}
推荐阅读
- c# - 从 NotFound() 取回不允许的 405 方法
- python-3.x - 将列表元素与列表合并并将其转换为字符串以转换为十进制
- python - Beautifulsoup - 收集 href 链接并创建链接列表
- javascript - Jquery:如何让多个变量值组合更改另一个变量
- django - Django:在过滤期间选择匹配的外键
- r - R函数中是否有一种方法可以以该行的单元格值作为参数迭代每一行?
- google-cloud-platform - Google Big Query 不适用于 Azure DevOps 托管的 ubuntu 代理
- db2 - DB2-SQL Select Query 根据字段值获取前几条记录
- java - 获取一年中的第 n 天
- android - 上传音频文件时,API 在邮递员中工作,但在 android 应用程序中不工作