【问题标题】:Migrating from React Router v2 to v4从 React Router v2 迁移到 v4
【发布时间】:2017-06-03 22:15:59
【问题描述】:

所以,我目前使用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 实际发生的任何导航的第一个迹象,这将如何工作?

【问题讨论】:

    标签: react-router react-router-v4 react-router-dom


    【解决方案1】:

    github 上非常有用的帖子,您可以在其中看到迁移到 v4 的所有重要部分。

    https://gist.github.com/kennetpostigo/7eb7f30162253f995cd4371d85c1e196

    还解释了如何处理子路由。基本上,你应该在 App.js 中放置一个 Match,这样这个父组件将负责它自己的子路由部分,每个父组件都以此类推。

    没试过,告诉我怎么回事!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 2017-09-14
      • 2017-10-04
      • 2022-01-17
      • 2017-12-22
      • 1970-01-01
      • 2018-02-10
      相关资源
      最近更新 更多