【发布时间】:2022-01-12 09:23:31
【问题描述】:
我有如下数据,
const arr_obj = [
{
id: '1',
children: [],
type: 'TYPE1',
},
{
id: '2',
children: [
{
id: '1',
children: [
{
//some attributes
}
],
type: 'MAIN',
},
{
id: '2',
children: [
{
//some attributes
}
],
type: 'MAIN',
},
{
id: '3',
children: [
{
//some attributes
}
],
type: 'MAIN',
},
]
type: 'TYPE2',
},
{
id: '3',
children: [
{
id: '4',
children: [
{
//some attributes
}
],
type: 'MAIN',
},
{
id: '5',
children: [
{
//some attributes
}
],
type: 'MAIN',
},
{
id: '6',
children: [
{
//some attributes
}
],
type: 'MAIN',
},
]
type: 'TYPE2',
}
]
我必须找出类型的计数:'MAIN'。这些“主要”将在类型内:“type2”
所以预期的计数是 6。
下面是代码,
const ParentComponent = () => {
const findCount = (arr_obj) => {
let count = 0;
const expectedCount = 2;
const loop = (children) => {
for (const obj of children) {
const { type, children } = obj;
if (type === 'TYPE2') {
loop(children);
} else if (type === 'MAIN') {
++count;
if (count > expectedCount) return;
}
}
};
loop(children);
return count > expectedCount;
};
const output = findCount(arr_obj);
return (
//some jsx rendering
);
}
上面的代码工作正常。但我想让循环(子)函数成为一个纯函数。我不知道该怎么做。
现在的问题是我在循环方法之外定义变量。 如何将所有内容定义为函数的参数,您可以将函数移到组件之外。
有人可以帮我解决这个问题吗?谢谢。
【问题讨论】:
-
“纯”函数是什么意思?
-
你有更多的嵌套级别吗?
-
@Ricky Mo:没有外部依赖。
-
@Nina Scholz:是的,它可以有。但主要是所需的类型在子数组中
-
@RickyMo:所以就像目前我在组件中定义了变量一样。我怎样才能把函数循环和其他需要的变量放在组件之外,使它成为一个纯函数,不处理外部的任何状态
标签: javascript reactjs