我在我的应用程序中使用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()
答案 0 :(得分:36)
当key
更改 - 这是该属性的目的时,React总是卸载并重新组装组件,以帮助React维护组件的“标识”。特别是,在使用React的CSS转换时需要它,因为在一个组件中设置动画并在另一个组件中设置动画的唯一方法是让它们成为单独的DOM节点。
因为您将{key: this.context.router.getCurrentPath()}
传递给handler
内的App
组件,所以React将卸载并重新安装handler
组件,即使它是相同的类型,任何时候{{ 1}}返回不同的值。解决方案是找到一个在做想要动画时更改的键,否则保持不变。