重新挂载子组件

child component re-mounting

我在渲染方法中有一个父组件 Dash 和一个名为 Team 的子组件(都是 类)

在它的渲染中我有:

<Route exact path='/team' component={() => <Team currCompany={this.state.currCompany} />} />

在此团队组件内:

渲染函数中:

 <List component="nav" aria-label="main mailbox folders">
                        {this.mapstructure()}

                 </List>

和映射结构函数:

 mapstructure() {
 

          return this.state.teammembers.map(member => (
        
              
                <StyledAccordion key={member.Id.toString()}>
                 //irrelevant details here
                 </StyledAccordion>
             
        
        
            ));
        }
   

父组件状态更新(不是任何 属性 会改变 Team 组件的道具,地图完全重做,重新创建手风琴控件。为了确认这一点,我做了一些日志记录和 componentDidMount() 每次 Dash 渲染时都会重复调用。

问题

您正在通过 Routecomponent 道具上的匿名函数渲染组件,这会为每个渲染创建一个 Team 的新“实例”。

Route render methods

When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render or the children prop

解决方案

使用 render 属性渲染 Team 组件并传递额外的属性。

<Route
  exact
  path='/team'
  render={() => <Team currCompany={this.state.currCompany} />}
/>