React如何有条件地使用useMemo



我仍然得到我的头周围的React挂钩,我试图使用useMemo有条件地基于不同的因素。

我的useMemo部分看起来像这样

const headers = React.useMemo(
() => [
{
Header: "Name",
accessor: "name",
Cell: AvatarCell,
emailAccessor: "email",
},
{
Header: "Country",
accessor: "country",
Filter: SelectColumnFilter,
filter: "equals",
Cell: Country,
},
{
Header: "Address",
accessor: "address",
Cell: Address,
},
],
[]
);

然而,我想根据所选择的语言更改headers,所以我试图使用' if语句,但这不起作用


if (language === 'en')
{
const columns = React.useMemo(
() => [
{
Header: "Name",
accessor: "name",
Cell: AvatarCell,
emailAccessor: "email",
},
{
Header: "Country",
accessor: "country",
Filter: SelectColumnFilter,
filter: "equals",
Cell: Country,
},
{
Header: "Address",
accessor: "address",
Cell: Address,
},
],
[]
);
}
if (language === 'de')
{
const columns = React.useMemo(
() => [
{
Header: "Name",
accessor: "name",
Cell: AvatarCell,
emailAccessor: "email",
},
{
Header: "Land",
accessor: "country",
Filter: SelectColumnFilter,
filter: "equals",
Cell: Country,
},
{
Header: "Adresse",
accessor: "address",
Cell: Address,
},
],
[]
);
}
but it fails to compile and I get a message saying that I called the react hook conditionally.
How can I use one or the other useMemo based on the value of `language`
Thanks in advance

为了做到这一点,您需要在useMemo钩子中使用if else逻辑。然后你会想要添加一个变量,这个变量作为一个依赖项被应用到逻辑中。下面是一个简单的示例,当语言被删除时,第一个头文件被更改。

你传递给useMemo钩子的只是一个函数,这意味着你可以在里面有非常复杂的逻辑。您不需要限制自己只返回一些常量和预定义的变量

const columns = React.useMemo(
() => [
{
Header: language==="de"?"de-name":"Name",
accessor: "name",
Cell: AvatarCell,
emailAccessor: "email",
},
{
Header: "Country",
accessor: "country",
Filter: SelectColumnFilter,
filter: "equals",
Cell: Country,
},
{
Header: "Address",
accessor: "address",
Cell: Address,
},
],
[language]
);

将逻辑放在useMemo内部函数中-对所有语言使用单个函数。将language添加到第二个参数数组中(这样当语言变化时,结果将被重新计算)

例如:

const columns = React.useMemo(() => {
if (language === 'en') {
return [
{
Header: "Name",
accessor: "name",
Cell: AvatarCell,
emailAccessor: "email",
},
{
Header: "Country",
accessor: "country",
Filter: SelectColumnFilter,
filter: "equals",
Cell: Country,
},
{
Header: "Address",
accessor: "address",
Cell: Address,
},
];
} else if (language === 'de') {
return [
{
Header: "Name",
accessor: "name",
Cell: AvatarCell,
emailAccessor: "email",
},
{
Header: "Land",
accessor: "country",
Filter: SelectColumnFilter,
filter: "equals",
Cell: Country,
},
{
Header: "Adresse",
accessor: "address",
Cell: Address,
},
];
}
}, [language]);

相关内容

  • 没有找到相关文章

最新更新