"反应路由器"警告解决方案并将根支持传递给子路由



有时我看到了众所周知的警告,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更改stateroutes是静态的,您不会看到任何警告。但我的问题是:我将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 Componentprops,但是如何呢?我不知道如何调用并保持组件内部的Root Componentprops需要propsRoot 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 冲突)

最新更新