如何使用typescript和react仅在特定条件为true的情况下将对象添加到数组中



我有一个像下面这样的数组,

const arr: Column<Data>[] = [
{
Header: 'Header1',
id: 'some_id1',
Cell: ({value}) => 
value ? (
<div>hello</div>
) : null,
} as ColumnWithId<Data>,
......
......
......
......
//many other objects present
]

现在,如果条件说是Check true,那么它应该添加另一个对象,这样数组就会像下面这样,

const arr: Column<Data>[] = [
{
Header: 'Header1',
id: 'some_id1',
Cell: ({value}) => 
value ? (
<div>hello</div>
) : null,
} as ColumnWithId<Data>,
{
Header: 'Header2',
id: 'some_id2',
Cell: ({value}) => 
value ? (
<div>hello</div>
) : null,
} as ColumnWithId<Data>,

......
......
......
......
//many other objects present
]

下面是的代码

const setColumns = ({isCheck} : {isCheck: boolean;}) => {
const columns: Column<Data>[] = [
{
Header: 'Header1',
id: 'some_id1',
Cell: ({value}) => 
value ? (
<div>hello</div>
) : null,
} as ColumnWithId<Data>,
......
......
......
......
//many other objects present
];
return columns;
};

const ParentComponent: React.FC<> = () => {
const columns = React.useMemo(() => 
setColumns({ isCheck }),
[isCheck]
);

return (
//some jsx
);
}

如果isCheck为true,我如何将另一个对象添加到数组中。我试过下面这样的东西。

const setColumns = ({isCheck} : {isCheck: boolean;}) => {
const columns: Column<Data>[] = isCheck ? [
{
Header: 'Header1',
id: 'some_id1',
Cell: ({value}) => 
value ? (
<div>hello</div>
) : null,
} as ColumnWithId<Data>,
{
Header: 'Header2',
id: 'some_id2',
Cell: ({value}) => 
value ? (
<div>hello</div>
) : null,
} as ColumnWithId<Data>,

......
......
......
......
//many other objects present
] : [
{
Header: 'Header1',
id: 'some_id1',
Cell: ({value}) => 
value ? (
<div>hello</div>
) : null,
} as ColumnWithId<Data>,
.....
.....
.....
.....
//many other objects present
];

return columns;
};

以上工作。但正如您所看到的,如果条件为true,我将复制同一个数组(其中包含许多其他对象(,并向数组中添加一个对象。通常这个数组有很多对象,像上面的setColumns方法那样在代码中复制它会使代码看起来很笨拙。

所以我在想一个更好的解决方案。有人能帮我做这个吗。我是编程新手。谢谢

您可以使用数组推送来完成此

const setColumns = ({isCheck} : {isCheck: boolean;}) => {
// Declare the initial array with the objects that should exist either way
const columns: Column<Data>[] =[
{
Header: 'Header1',
id: 'some_id1',
Cell: ({value}) => 
value ? (
<div>hello</div>
) : null,
} as ColumnWithId<Data>,
.....
.....
.....
.....
//many other objects present
];
// Conditionally add the additional element
if(isCheck){
columns.push({
Header: 'Header2',
id: 'some_id2',
Cell: ({value}) => 
value ? (
<div>hello</div>
) : null,
} as ColumnWithId<Data>
)
}
return columns;
};

相关内容

最新更新