[英]`react-router` warning solution and passing root props to sub routes
有時我看到了眾所周知的警告, browser.js:49 Warning: [react-router] You cannot change <Router routes>; it will be ignored
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>
)
}
}
這是可行的,消除[react-router]警告的絕佳解決方案,對於Root Component
更改state
, routes
是靜態的,您將看不到任何警告。 但我的問題是:我將Root Component
道具傳遞給每個Route
並且我無法執行上述解決方案😞,我必須將App Route
放入Router中,所以這個方法絕對不是解決方法,我會再次看到已知警告,請參閱我的路由器代碼:
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
S和使用它們。 我怎么能看到警告並將道具傳遞到任何Route
?
我的一個解決方案是,我寫的所有Route
S作為靜態和調用Root Component
props
直接在每個組件內,但如何? 我不知道我怎么能叫,並保持props
的Root Component
需要有組件內props
的Root Component
作為組件不是直接Root Component
的孩子嗎?
您可以使用render
route prop而不是component
來將props傳遞給組件:
<Route path="/transaction" render={() => <Transaction {...this.props} />} />
編輯:或者這也傳遞路徑道具:
<Route path="/transaction" render={(routeProps) => <Transaction parentProps={this.props} {...routeProps} />} />
(我認為最好將單個自定義父道具傳遞給不與routeProps沖突)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.