是否可以在 react-router 转换中仅重新安装新的 child 组件

Is it possible to only remount only the new child components on react-router transition

我在我的应用程序中使用 react-router,我正在寻找一种方法来停止重新安装 DOM 中已有的组件。例如,如果我在 URL dashboard,那么我将安装一个关联的 DashboardComponent。当我过渡到 dashboard/settings 时,我的 DashboardComponentSettingsComponent 会重新装入 DOM。我想找到一种干净的方法来仅挂载当前 URL 的 children。这可能吗?

路由器:

import { Component, createFactory, PropTypes } from 'react'
import { Route, RouteHandler, DefaultRoute, NotFoundRoute } from 'react-router'

import Home from '../components/Home'
import Dashboard from '../components/Dashboard'
import ViewPlayers from '../components/clubs/ViewPlayers'

let route = createFactory(Route),
    handler = createFactory(RouteHandler),
    root = createFactory(DefaultRoute),
    pageNotFound = createFactory(NotFoundRoute),
    Transitions = createFactory(require('react/lib/ReactCSSTransitionGroup'));

class App extends Component {

    constructor() {

        super();
    }

    render() {

        return (
            Transitions({transitionName: 'fade'},
                handler({key: this.context.router.getCurrentPath()})
            )
        )
    }
}
App.contextTypes = {
    router: PropTypes.func
};

let Router = (
    route({path: '/', name: 'home', handler: App},
        root({handler: Home}),
        route({path: 'dashboard', name: 'dashboard', handler: Dashboard},
            route({path: 'players', name: 'players', handler: ViewPlayers}),
        )
    )
);
export { Router };

仪表板(Parent 组件):

import React from 'react'
import { RouteHandler, Link } from 'react-router'
import { _, div } from './Html'

export default
class Dashboard extends React.Component {

    constructor() {

        super();

        this.state = {}
    }

    componentWillMount() {

        console.log('mounted')
    }

    componentWillUnmount() {

    }

    render() {

        return (
            div({},
                _(Link)({to: 'players'}),
                _(RouteHandler)({})
            )
        )
    }
}

注意: _ 只是 React.createFactory()

的包装

React 总是在 key 发生变化时卸载并重新安装组件——这就是 属性 的目的,以帮助 React 维护组件的 "identity"。特别是,在使用 React 的 CSS 转换时需要它,因为使一个组件动画化并在另一个组件中动画化的唯一方法是让它们成为单独的 DOM 节点。

因为您将 {key: this.context.router.getCurrentPath()} 传递给 App 内的 handler 组件,React 将随时卸载并重新安装 handler 组件,即使它是同一类型getCurrentPath() returns 不同的值。解决方案是找到一个键,该键在您 想要设置动画时发生变化,但在其他情况下保持不变。