Pet*_*ter 2 reactjs material-ui react-hooks
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>
))}
Run Code Online (Sandbox Code Playgroud)
我的翻译功能如下所示:
import { useSelector } from "react-redux";
export const useTranslations = () =>
useSelector(state => state.translations.data, []);
Run Code Online (Sandbox Code Playgroud)
如果我将一个字符串传递给它,翻译函数就会按预期工作。但是,如果我替换{useTranslation(row.label)}为{row.label},则不会再收到错误消息。在我看来,我不会在这里的循环、条件或嵌套函数中调用 Hook,还是我错了?
您有一个呈现单元格列表的组件。但是这里的每个单元格都由传递给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} />
))}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4244 次 |
| 最近记录: |