所以,我目前正在使用 react-router
v2,如下所示:
import { IndexRoute, Router, Route, Redirect } from 'react-router';
import App from './components/App';
....
render () {
return (
<ApolloProvider store={store} client={client}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={PhotoGrid} />
<Route path="/view/:postId" component={Single}></Route>
<Route path="/login" component={LoginUser}></Route>
</Route>
</Router>
</ApolloProvider>
)
}
}
export default MainApp;
App.js
....
import Main from './Main';
const allPostsCommentsQuery = graphql(All_Posts_Comments_Query, {
options: {
cachePolicy: 'offline-critical',
fetchPolicy: 'cache-first',
},
});
function mapStateToProps(state) {
return {
auth: state.auth
};
}
export const mapDispatchToProps = (dispatch) => {
return bindActionCreators(actionCreators, dispatch);
}
export default compose(
allPostsCommentsQuery,
connect(mapStateToProps, mapDispatchToProps)
)(Main);
Main.js
class Main extends React.Component {
constructor (props) {
super(props);
}
componentWillMount () {
if (!this.props.auth.token){
this.context.router.push('/login');
}
}
render () {
return (
<div>
<h1>
<Link to="/">Flamingo City</Link>
</h1>
{ React.cloneElement(this.props.children, this.props) }
</div>
);
}
}
Main.contextTypes = {
router: function() { React.PropTypes.func.isRequired }
};
export default Main;
如何将当前的 v2 路由器转换为 v4?我不清楚的是父嵌套元素:
<Route path="/" component={App}>
在我迄今为止看到的所有 v2 -> v4 转换示例中,没有一个清楚地解释了子元素会发生什么。我是否希望将子元素放置在 App.js 组件本身中?如果是,在我的 App.js 版本中,作为任何导航的第一个标志实际上是在 Main.js 中发生的,这将如何工作?
最佳答案
github 上非常有用的帖子,您可以在其中看到迁移到 v4 的所有重要部分。
https://gist.github.com/kennetpostigo/7eb7f30162253f995cd4371d85c1e196
还解释了如何进行子路线。基本上,您应该在 App.js 中放置一个 Match,以便该父组件将负责自己的子路由部分,每个父组件也是如此。
还没试过,请告诉我效果如何!
关于react-router - 从 React Router v2 迁移到 v4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44349020/