是否可以仅在反应路由器转换

时间:2015-08-04 15:36:42

标签: 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 };

仪表板(父组件):

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()

的包装器

1 个答案:

答案 0 :(得分:36)

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

因为您将{key: this.context.router.getCurrentPath()}传递给handler内的App组件,所以React将卸载并重新安装handler组件,即使它是相同的类型,任何时候{{ 1}}返回不同的值。解决方案是找到一个在想要动画时更改的键,否则保持不变。