2

所以,我目前使用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;

应用程序.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);

主.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 实际发生的任何导航的第一个迹象,这将如何工作?

4

1 回答 1

2

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

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

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

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

于 2017-07-27T11:29:35.940 回答