有时我看到了众所周知的警告,browser.js:49 Warning: [react-router] You cannot change <Router routes>; it will be ignored
和我发现了两个趋势问题,朋友们讨论了这个问题,解决方案是const
路由组件并将它们放在组件Router
。
https://github.com/ReactTraining/react-router/issues/2704
https://github.com/reactjs/react-router-redux/issues/179
就像下面一样:
您将看到带有以下代码的警告:
class Root extends Component {
render() {
return (
<Router history={browserHistory} createElement={this.createElement}>
<Route component={App}>
<Route path="/" component={MainPage}/>
<Route path="/page2" component={Page2}/>
<Route path="/settings" component={SettingsPage}/>
</Route>
</Router>
)
}
}
但您不会看到以下代码的警告:
const routes = (
<Route component={App}>
<Route path="/" component={MainPage}/>
<Route path="/page2" component={Page2}/>
<Route path="/settings" component={SettingsPage}/>
</Route>
);
class Root extends Component {
render() {
return (
<Router history={browserHistory} createElement={this.createElement}>
{routes}
</Router>
)
}
}
这没关系,消失[反应路由器]警告的真棒解决方案,并且对于Root Component
更改state
,routes
是静态的,您不会看到任何警告。但我的问题是:我将Root Component
道具传递给每个Route
,但我无法执行上述解决方案😞, 我必须将应用程序Route
放入路由器中,因此使用此方法绝对不是解决方案,我将再次看到已知警告,请参阅我的路由器代码:
export default class AppRoutes extends Component {
render() {
return (
<Router history={hashHistory}>
<Route path="/" {...this.props} component={App}>
<IndexRoute component={Home} {...this.props}/>
<Route path="/transaction" component={Transaction} {...this.props}/>
<Route path="/users-management" component={UsersManagement} {...this.props}/>
<Route path="/issues" component={Issues} {...this.props}/>
<Route path='/not-found' component={NotFound}/>
<Route path='/settlement-management' component={SettlementManagement} {...this.props}/>
<Route path='/categories-management' component={CategoriesManagement} {...this.props}/>
<Route path='/gifts-management' component={GiftsManagement} {...this.props}/>
<Redirect from='/*' to='/not-found'/>
</Route>
</Router>
);
}
}
渲染代码Root Component
是:
render(){
return(
<AppRoutes {...this}/>
);
}
我将其作为道具传递给AppRoutes
组件,我需要将继承的this.props
传递给子Route
并使用它们。 我怎么可能看不到警告并将道具传递给任何Route
?
我的解决方案之一是,我将所有Route
编写为静态,并直接在每个组件中调用Root Component
props
,但是如何呢?我不知道如何调用并保持组件内部的Root Component
props
需要props
Root Component
,因为该组件不是直接Root Component
子组件?
您可以使用render
路由 prop 而不是component
将 prop 传递给您的组件:
<Route path="/transaction" render={() => <Transaction {...this.props} />} />
编辑:或者这也传递路由道具:
<Route path="/transaction" render={(routeProps) => <Transaction parentProps={this.props} {...routeProps} />} />
(我认为最好传递单个自定义父道具,以免与 routeProps 冲突)