首页 > 解决方案 > 使用 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,还是我错了?

标签: reactjsmaterial-uireact-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} />
))}


推荐阅读