app.js
import React, { Component } from 'react';
import {Route, Switch,Redirect} from 'react-router-dom';
import Layout from './hoc/Layout/Layout';
import BurgerBuilder from './containers/BurgerBuilder/BurgerBuilder';
import Logout from './containers/Auth/Logout/Logout';
import {connect} from 'react-redux';
import * as actions from './store/actions/index';
import asyncComponent from './hoc/asyncComponent/asyncComponent';
const asyncCheckout = asyncComponent(()=>{
return import('./containers/Checkout/Checkout');
});
const asyncOrders = asyncComponent(()=>{
return import('./containers/Orders/Orders');
});
const asyncAuth = asyncComponent(()=>{
return import('./containers/Auth/Auth');
});
//每次route都会loaded——可用于判断auth状态
class App extends Component {
componentDidMount(){
this.props.onTryAutoSignup();
};
render () {
//设置不同状态下能访问的页面
let routes = (
<Switch>
<Route path="/auth" component={asyncAuth}/>
<Route path="/" exact component={BurgerBuilder}/>
<Redirect to='/'/>
</Switch>
);
if(this.props.isAuthenticated){
routes = (
<Switch>
<Route path="/checkout" component={asyncCheckout}/>
<Route path="/orders" component={asyncOrders}/>
<Route path="/logout" component={Logout}/>
<Route path="/auth" component={asyncAuth}/>
<Route path="/" exact component={BurgerBuilder}/>
<Redirect to='/'/>
</Switch>
);
};
return (
<div>
<Layout>
{routes}
</Layout>
</div>
);
}
}
const mapStateToProps = state=>{
return{
isAuthenticated: state.auth.token !== null
};
};
const mapDispatchToProps = dispatch=>{
return {
onTryAutoSignup: ()=>dispatch(actions.authCheckState())
};
};
export default connect(mapStateToProps,mapDispatchToProps)(App);
lazyLoading.js
import React,{Component} from 'react';
const asyncComponent = (importComponent) =>{
return class extends Component{
state = {
component : null
};
componentDidMount(){
importComponent() //动态引入component
.then(cmp=>{
this.setState({component: cmp.default});
});
};
render() {
const C = this.state.component;
return C?<C {...this.props} /> : null;
}
}
}
export default asyncComponent;