Reactjs 选择性子组件渲染

Reactjs 选择性子组件渲染,reactjs,react-redux,Reactjs,React Redux,一个基本问题,我需要帮助。 每当在父组件上调用this.setState时,将呈现所有子组件。如果我有大量的子组件,这将导致性能问题 举个例子, 父组件 handleToggleTick() { const newObj = Object.assign({}, this.state, { iconName: ''}); this.setState({ iconName: newObj.iconName, }); } render() { return(

一个基本问题,我需要帮助。 每当在父组件上调用this.setState时,将呈现所有子组件。如果我有大量的子组件,这将导致性能问题

举个例子,

父组件

handleToggleTick() {
    const newObj = Object.assign({}, this.state, { iconName: ''});
    this.setState({
      iconName: newObj.iconName,
    });
}

render() {
  return(
    <ChildComponentA iconName={this.state.iconName} toggleTick={() => this.handleToggleTick}></ChildComponentA>
    <ChildComponentB></ChildComponentA>
    <ChildComponentC></ChildComponentA>
  )
}
handleToggleTick(){
const newObj=Object.assign({},this.state,{iconName:'});
这是我的国家({
iconName:newObj.iconName,
});
}
render(){
返回(
this.handleToggleTick}>
)
}
基于上述示例,每当从childcomponentA调用handleToggleTick时,都会为新的iconName调用setState。我想要的是,仅限ChildComponent A只有一个获得render,因为props.iconName与之相关,但不适用于ChildComponent B和ChildComponent C

我知道有一个选项可以检查childcomponent中的shouldComponentUpdate,以防止它得到渲染。但是,假设我有超过100个childcomponent,写超过100次shouldComponentUpdate方法会令人沮丧吗


我需要帮助,请指教

< P>另一个您可以考虑的解决方案是将代码> > ICONNEX/CODE >转换成<代码> ChildComponentA <代码>,考虑到这是与它相关的唯一组件。

< P>反应不能提供选择性地呈现孩子的任何方式。该组件将渲染或不渲染。但我需要强调几点,为什么在实践中使用React时这不是一个问题

首先,您不需要为每个组件手动实现
shouldComponentUpdate
。如果您不想在组件的道具和状态没有改变的情况下重新渲染组件,您可以从类而不是
组件
类进行扩展。请注意,
React.PureComponent的
shouldComponentUpdate()
仅对状态和道具使用浅层比较。但如果您遵循react最佳实践并避免改变状态,这应该不会成为问题

此外,在一种渲染方法中使用超过100个不同的组件也不切实际。React始终鼓励将UI分解为更小的组件并使用组件组合。当我们采用这种方法时,组件将以不同的级别相互嵌套,而不是在一个渲染方法中有大量组件

我试图解释的是,当我们以嵌套方式(2)组合组件时,它比在一个大容器组件(1)中包含大量组件更实用、更易于管理

在您的示例中,如果ChildComponentB和ChildComponentC位于另一个名为ChildConatainerComponent的组件中,那么我们只需要为ChildConatainerComponent实现
shouldComponentUpdate()
。然后它将自动停止渲染其中的任何子元素

render() {
  return(
    <ChildComponentA iconName={this.state.iconName}
      toggleTick={() => this.handleToggleTick}/>
    <ChildConatainerComponent/>
  )
}

class ChildConatainerComponent extends PureComponent {
  render() {
    return (
      <div>
       <ChildComponentB/>
       <ChildComponentC/>
      </div>
    );
  }
}
render(){
返回(
this.handleToggleTick}/>
)
}
类ChildConatainerComponent扩展了PureComponent{
render(){
返回(
);
}
}

要记住的另一个非常重要的概念是调用
render
函数并不意味着React会再次创建所有DOM元素。
render
方法只对React虚拟DOM进行更改,虚拟DOM是DOM的内存表示形式,比实际DOM更快。然后比较更新前和更新后的虚拟DOM版本,实际DOM将只更新实际更改的内容。

Hi Joe,感谢您的快速回复。但我的设计是,父组件充当容器,因为ChildComponent A是我的哑组件。所以,哑组件只用于表示,父组件应该处理状态。我明白了。然后我相信您必须使用
shouldComponentUpdate
。谢谢,我现在有了这个想法。尝试在子组件上使用
React.memo
export default React.memo(mycop)