[英]React: Child Component Filtering Parent Component Props
我很困惑为什么这不起作用。 我可以进行 API 提取,并很好地过滤数据。 但是,父组件已经获取了这个数据,所以我需要使用它而不做另一个调用。
父组件:(我想在此组件的子组件中过滤contacts
中的数据集)
class Database extends Component {
constructor(props){
super(props);
this.state = {
clients: [],
contacts: []
}
}
我将对象的contacts
数组传递给子组件,如下所示:
<Container className="database">
{this.state.clients.map(client => (
<ClientCard
key={client.id}
short={client.short}
client={client.client}
{...this.state}
/>
))}
</Container>
然后在我的子组件中,我正在过滤contacts
数据以在我的子组件中使用,所以我有一个开头的 state:
class ClientCard extends Component {
constructor(props){
super(props);
this.state = {
showHide: false,
filteredContacts: []
}
所以我现在想做的是在componentDidMount
上,像这样过滤道具数据:
this.setState({
filteredContacts: this.props.contacts.filter(contact => this.props.contacts.short === this.props.short)
});
我没有收到任何错误,但它也没有根据需要设置filteredContacts
的state。 代码中提到的short
是作为 object 属性存储在数组中的客户端的缩写,我用来帮助我过滤。
您需要使用传递给过滤器 function 的contact
来过滤该数组中的联系人。 大概每个contact
都有一个short
属性,您希望将其与组件的 prop short
进行比较。
this.setState({
filteredContacts: this.props.contacts.filter(contact => contact.short === this.props.short)
});
不应该有this.props.contacts.short
因为this.props.contacts
是一个数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.