【问题标题】:How to not render concrete components in render method in REACT 17.0如何在 REACT 17.0 的渲染方法中不渲染具体组件
【发布时间】:2024-04-14 00:30:01
【问题描述】:

在我的组件的渲染方法中,我创建了十几个其他组件的实例,其中一些组件(例如标题、下拉菜单、过滤器)不需要在每次更新其父组件后渲染。 我可以将标志设置为 true,然后在 componentDidMount() 中将其重置为 false,但我认为可能会有更好、更好、更清洁的方法。 这里我介绍一下我的组件的渲染方法

render() {
        console.log("som v render weather list")


        const currentWeathers = this.getWeathersOnSpecificPage()
        const filters = <FiltersComponent key={nanoid()} temperatureUnits = {this.state.temperature.units} countries = {this.state.countries}
        descriptions = {this.state.descriptions} onChangeMethod={this.onChangeFilter} />

        const pagination = <Pagination key={nanoid()} currentPage={this.state.currentPage} showPages={this.state.showPages}
        itemsPerPage = {this.state.itemsPerPage} totalItems = {this.state.weathers.length} paginate={this.paginate}/>

        const temperatureDropdown = temperatureDropdownList( (units, abbreviation ) => {
            this.setState({"temperature": {"units" : units, "abbreviation" : abbreviation}})
        })

        let container= [temperatureDropdown, filters, pagination]

        if (this.state.weathers)
            container.push(<table key={nanoid()} className="weatherTable">
                {this.header()}
                {this.mainBody(currentWeathers, this.state.temperature)}
            </table>
            )

        return (
            <div className="container">
             {container}
            </div>
        )
         
    }

【问题讨论】:

    标签: javascript reactjs class components render


    【解决方案1】:

    您可以使用React.PureComponent 这样,组件将进行浅比较,并且仅在发生更改时才会重新渲染。

    如果你有一个功能组件,你应该useMemo

    【讨论】:

    • 好的,所以我在您的链接中读到要使用它,我使用 React.PureComponent 扩展了我的类组件。如果我在处理函数组件怎么办。
    最近更新 更多