【问题标题】:React: Child Component Filtering Parent Component PropsReact:子组件过滤父组件道具
【发布时间】:2021-05-22 00:16:36
【问题描述】:

我很困惑为什么这不起作用。我可以进行 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 数据以在我的子组件中使用,所以我有一个开始状态:

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 的状态。代码中提到的short 是存储在数组中的客户端的缩写,作为我用来帮助我过滤的对象属性。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您需要使用传递给过滤器函数的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 是一个数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 2019-12-19
      • 2020-10-02
      相关资源
      最近更新 更多