React: 如何在props中过滤一个对象数组

3

我有以下数据的props

test1: abc
id: 1
myArray: Array(3)
0: {a:abc, b:cde, aid: 1}
1: {e:age, f:ade, aid: 2}
2: {t:are, h:had, aid: 1}

我希望能够筛选props并更新数组,只留下与idaid相匹配的值。

因此,props应如下所示:

test1: abc
id: 1
myArray: Array(3)
0: {a:abc, b:cde, aid: 1}
2: {t:are, h:had, aid: 1}

我该怎么做呢?


我本来想发布一个过滤器实现,但有一个细节,props是不可变的...这是正确的吗?你想改变当前组件的props吗? - Facundo Larrosa
3个回答

1
您可以使用以下代码获取过滤后的数据:

``````

const filteredData = this.props.myArray.filter(item => item.aid === 1)

然而,props 只是可读的。您必须要么分发或更新父组件以提供新的/过滤后的数据作为 props。


我是React的新手。useState能否用于根据过滤列表更新状态?比如,如果我从prop变量中筛选出3个列表,我应该有3个单独的状态吗?谢谢! - Upulie Han
找到了!从props中过滤和创建新变量应该涉及使用useState,这些useState在useEffect中被调用。 - Upulie Han

1
你可以使用 filter 数组方法。
let myArray = [{a:"abc", b:"cde", aid: 1},
               {e:"age", f:"ade", aid: 2},
               {t:"are", h:"had", aid: 1}]

const result = myArray.filter(item => item.aid === 1)

console.log(result)

但请注意,props是不可变的。
如果您希望永久更改此prop,则需要在父组件中更新它

0

你可以使用 Array.filter()

// match both a AND aid
const result = myArray.filter(obj => (obj.a === test1 && obj.aid === id);
// match either a OR aid
const result = myArray.filter(obj => (obj.a === test1 || obj.aid === id);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接