我在应用程序中使用react-router,并且正在寻找一种方法来停止重新安装DOM中已经存在的组件。例如,如果我在URL dashboard,那么我将有一个关联的DashboardComponent挂载。当我过渡到DOM时,dashboard/settings我DashboardComponent也SettingsComponent将其重新安装到DOM中。我想找到一种干净的方法来仅挂载当前URL的子级。这可以吗?
dashboard
DashboardComponent
dashboard/settings
SettingsComponent
路由器:
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()的包装
_
React总是在组件key更改时卸载并重新安装组件,这就是该属性的目的,以帮助React维护组件的“身份”。特别是,在使用React的CSS过渡时,这是必需的,因为使一个组件具有动画效果并在另一个组件中进行动画效果的唯一方法是使它们成为单独的DOM节点。
key
因为您传递{key: this.context.router.getCurrentPath()}给handler内部App的handler组件,所以即使它是相同类型,React也将卸载并重新安装该组件,任何时候都getCurrentPath()将返回不同的值。解决办法是找到当你改变的关键 不 希望动画,但停留否则相同。
{key: this.context.router.getCurrentPath()}
handler
App
getCurrentPath()