gpt4 book ai didi

javascript - react 如何有条件地使用 useMemo

转载 作者:行者123 更新时间:2023-12-05 02:40:08 25 4
gpt4 key购买 nike

我仍然在思考 React hooks,并尝试根据不同的因素有条件地使用 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 Hook 中包含 if else 逻辑。然后您将要添加逻辑正在应用的变量作为依赖项。下面是一个简单的示例,其中第一个 header 在语言为 de 时发生更改。

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

  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]
);

关于javascript - react 如何有条件地使用 useMemo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68733169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com