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

Jul*_*ent 8 reactjs react-router

我在我的应用程序中使用react-router,我正在寻找一种方法来停止已经在DOM中的组件的重新安装.例如,如果我在URL dashboard,那么我将有一个关联的DashboardComponent挂载.当我转换到dashboard/settings那时我DashboardComponent以及SettingsComponent重新安装到DOM中.我想找到一种干净的方法来只挂载当前URL的子节点.这是真的吗?

路由器:

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 };
Run Code Online (Sandbox Code Playgroud)

仪表板(父组件):

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)({})
            )
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

注意: _只是React.createFactory()的包装器

Mic*_*ley 40

React总是卸载并重新组装组件,当它的key更改 - 这是该属性的目的时,以帮助React维护组件的"标识".特别是,在使用React的CSS转换时需要它,因为在一个组件中制作动画并在另一个组件中制作动画的唯一方法是让它们成为单独的DOM节点.

因为你传递{key: this.context.router.getCurrentPath()}handler里面的组件App,React将卸载并重新安装handler组件,即使它是相同的类型,任何时候都会getCurrentPath()返回不同的值.解决办法是找到改变,当你一键想动画,但在其他方面保持不变.