我有一个名为 Root
的组件它呈现了我的 index.js
的路线
const store = configureStore();
ReactDOM.render(
<Root store={store} />,
document.getElementById('root'),
);
我需要这样做,因为我正在连接 Root
至redux
,这是由于 root 授权 onEnter
,并且它需要与 redux
一起使用状态。
所以这是根:
class Root extends React.Component {
constructor(props) {
super(props);
// some stuff
}
requireAuthentication = (nextState, replace) => {
// some stuff for managing auth
};
render() {
const { store } = this.props;
return (
<div>
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route component={Dashboard}>
<IndexRoute component={Home} onEnter={requireAuthentication}/>
</Route>
<Route path="login" component={Login} />
</Route>
</Router>
</Provider>
</div>
);
}
}
// some definitions for connecting Root to redux
export default connect(mapStateToProps, mapDispatchToProps)(Root);
好吧...这渲染得很好,但我有一个警告:
Warning: [react-router] You cannot change <Router routes>; it will be ignored
路线,也工作正常......但我想解决警告。所以...谷歌搜索我发现这个问题是一个可能的解决方案:声明 routes
在构造函数内并将其传递给 Router
通过props
.
我的构造函数我这样做了:
import React, { PropTypes } from 'react';
import { connect, Provider } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Router, browserHistory, Route, IndexRoute } from 'react-router';
import { loginActions } from '../actions';
import { App, Dashboard, Home, Login } from '../features';
import adalHandler from '../services/adal';
class Root extends React.Component {
constructor(props) {
super(props);
const routes = (
<Route path="/" component={App}>
<Route component={Dashboard}>
<IndexRoute component={Home} />
</Route>
<Route path="login" component={Login} />
</Route>
);
// some stuff
}
}
requireAuthentication = (nextState, replace) => {
// stuff
};
render() {
const { store } = this.props;
return (
<div>
<Provider store={store}>
<Router history={browserHistory} routes={this.routes} />
</Provider>
</div>
);
}
}
// stuff
export default connect(mapStateToProps, mapDispatchToProps)(Root);
但是现在渲染不好。
如何解决?
最佳答案
渲染方法中 undefined object this.routes
。
例如,您可以将构造函数中的 const paths = (...);
替换为 this.routes = (...);
以使对象可以在渲染方法。
关于javascript - 在构造函数中定义路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41901306/