【发布时间】:2020-01-21 03:12:22
【问题描述】:
我有类别数组,其中包含专业化的对象数组。当我试图按专业过滤它时,出现了问题(不能更改并保存所有数据的类别列表,它也发生了变化。当我从数据搜索列表中删除字母时不会回来)。我尝试了很多方法,最后代码变成了这样(我知道这不是很好的代码,但我尝试了很多东西,只是打字很累);
这是我的过滤方法:
this.setState(prevState => {
const { categories } = prevState;
let filtered = [];
for (let i = 0; i < categories.length; i++) {
let newCategory = categories[i];
const { specializations } = categories[i];
let newSpecs = [];
for (let j = 0; j < specializations.length; j++) {
const { specName } = specializations[j];
if (specName.indexOf(search) !== -1) {
newSpecs.push(specializations[j]);
}
};
newCategory.specializations = newSpecs;
if (newSpecs.length>0) {
filtered.push(newCategory);
}
}
return {resultCategories:filtered}
});
这就是我的渲染方式:
category.specializations.map(
(spec, index) =>
(index < 5 || collapsed[cat_index]) && (
<Text
onPress={() =>
this.props.navigation.navigate("CreateOrderSecond", {
spec: spec.id
})
}
style={styles.specs}
key={index}
>
{spec.specName}
</Text>
)
);
类别看起来如何:
Category{
avatar Image{...}
categoryName string
created string($date-time)
id integer($int64)
lastUpdated string($date-time)
specializations [Specialization{
avatar Image{...}
created string($date-time)
id integer($int64)
lastUpdated string($date-time)
masterName string
specName string
}]
}
【问题讨论】:
-
请说明您的实际 json 是什么样的以及您想要的 json 是什么?
-
我包含了类别的 Swagger 模型。类别中有一系列专业化,我只需要通过搜索字符串过滤专业化列表
-
您想要针对每个类别的专业化?
-
是的,专业化必须保留在类别中
-
看起来某些东西是通过引用而不是值传递的,所以当您只想使用值而不修改原始对象时,您的原始对象正在被修改。您必须传递/复制对象而不仅仅是分配它,这恰好是通过引用。 (我没有在这里详细介绍,但我认为这是最有可能发生的)
标签: javascript arrays reactjs react-native