我在我的应用程序中使用 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() 的包装器