代码之家  ›  专栏  ›  技术社区  ›  InesM

防止状态更改时响应路由卸载组件

  •  0
  • InesM  · 技术社区  · 7 年前

    我正在使用React Router(v.4.3.1)呈现我的应用程序的主要部分,我在左侧有一个抽屉,上面有菜单。当在app头中切换按钮时,我会更改折叠变量的状态,以便组件可以相应地重新呈现css。我的问题是这个变量需要存储在呈现所有 Route 当组件更新时 路线 正在卸载和安装它的组件。

    我已经尝试提供 key 对我 路线 但它不起作用。

    我的代码看起来像这样,并且这个组件的父级是正在更新的,它重新呈现我的 Main 组件:

    class Main extends Component {
        constructor(props) {
            super(props);
            this.observer = ReactObserver();
        }
    
        getLayoutStyle = () => {
            const { isMobile, collapsed } = this.props;
            if (!isMobile) {
                return {
                    paddingLeft: collapsed ? '80px' : '256px',
                };
            }
            return null;
        };
    
        render() {
            const RouteWithProps = (({index, path, exact, strict, component: Component, location, ...rest}) =>
                    <Route path={path}
                           exact={exact}
                           strict={strict}
                           location={location}
                           render={(props) => <Component key={"route-" + index} observer={this.observer} {...props} {...rest} />}/>
            );
    
            return (
                <Fragment>
                    <TopHeader observer={this.observer} {...this.props}/>
                    <Content className='content' style={{...this.getLayoutStyle()}}>
                        <main style={{margin: '-16px -16px 0px'}}>
                            <Switch>
                                {Object.values(ROUTES).map((route, index) => (
                                    <RouteWithProps {...route} index={index}/>
                                ))}
                            </Switch>
                        </main>
                    </Content>
                </Fragment>
            );
        }
    }
    

    我希望路由只是更新而不是卸载组件。这有可能吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Shevchenko Viktor    7 年前

    由于定义了 RouteWithProps 渲染方法内部。这将导致每次调用render方法时对卸装旧的和装入新的作出反应。在渲染方法中动态地创建组件是一个性能瓶颈,被认为是一种糟糕的实践。

    只需移动的定义 道具 由于 Main 组件。

    大致的代码结构如下:

    // your impors
    
    const RouteWithProps = ({observer, path, exact, strict, component: Component, location, ...rest}) =>
         <Route path={path}
             exact={exact}
             strict={strict}
             location={location}
             render={(props) => <Component observer={observer} {...props} {...rest} />}/>;
    
    class Main extends Component {
        ...
    
        render(){
            ...
            {Object.values(ROUTES).map((route, index) => (
                <RouteWithProps key={"route-" + index} {...route} observer={this.observer}/>
            ))}
                                ^^^ keys should be on this level
            ...
        }
    }