首页 > 解决方案 > How do I unload components?

问题描述

I have project component that I'm duplicating according to a project list. Once the page is rendered and all Project components are displayed I want to enable a search functionality.

When I perform the search and I filter the project list, the old results are displayed near the new results after search!

How to cause it to display only search results?

Updated code (Working):

class ProjectsList extends Component {

state = {
    projectsDetails: [......],
    filterKey: null
}

componentWillMount() {
    //service.getProjectDetails();
}

handleSearchChange(e) {
    this.setState({ filterKey: e.target.value });
}

render() {
    const { filterKey, projectsDetails } = this.state;

    const filteredProjects = filterKey
        ? projectsDetails.filter(item =>
            item.Name.toLowerCase().includes(filterKey.toLowerCase()) && item.FabricationConfigs !== null
        )
        : projectsDetails.filter(item =>
            item.FabricationConfigs !== null
        );

    return (
        <table width="100%">
            <tbody>
            <tr>
                <td>

                    <div className="Toolbar2">
                        <table width="100%">
                            <tbody>
                            <tr>
                                <td>
                                    <h1>Projects</h1>
                                </td>
                                <td  width="20%" align="right">
                                    <Search labelText="" id="search-1" onChange={ this.handleSearchChange.bind(this) }/>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                        <hr></hr>
                    </div>
                    <div className="inline">
                        {filteredProjects.map(item =>
                            <Project
                            key={item.Name}
                            name={item.Name}
                            description={item.Description}
                            configurations={item.FabricationConfigs}/>)}
                    </div>

                </td>
            </tr>
            </tbody>
        </table>
    );
}

}

标签: javascriptreactjsreact-reduxunmount

解决方案


假设您正在渲染一个列表:

state = {
  list: [{code: 'a'},{code: 'b'},{code: 'c'}],
};

//some render function
<div>{this.state.list.map(item => <Item item={item} />}</div>

为了不卸载这些项目之一,您必须取消渲染它们。

因此您可以按索引删除一个(例如)。您可以使用您的功能进行过滤。

removeByIndex(idx) {
  this.setState({
    list: this.state.list.filter((item, index) => index !== idx),
  });
}

因此,具有所述索引的Item组件将被取消渲染并因此被卸载。


推荐阅读