2017-06-03 41 views
1

所以,我目前使用react-router V2如下:遷移做出反應路由器V2到V4

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一起出現的?

回答

1

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

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

還解釋如何去了解孩子的路線。基本上,你應該在App.js中放置一個Match,這樣這個父組件就會對它自己的子路由部分負責,對每個父組件都是這樣。

還沒有試過這個,讓我知道它是怎麼回事!