React中使用loadable -- 异步加载
地址:https://www.npmjs.com/package/react-loadable
用法:
lodable.js:
// lodable.js 异步加载---异步加载详情页 import React from 'react' import Loadable from 'react-loadable'; const LoadableComponent = Loadable({ loader: () => import('./'), loading () { // 使用jsx语法必须引入 React return <div>正在加载</div> } }); // export default class App extends React.Component { // render() { // return <LoadableComponent/>; // } // } // eslint-disable-next-line import/no-anonymous-default-export export default () => <LoadableComponent />
Detail下的index.js: (没有引用到lodable)
import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { withRouter } from 'react-router-dom'; import { DetailWrapper, Header, Content } from './style' import { actionCreators } from './store' class Detail extends PureComponent { render () { return ( <DetailWrapper> <Header>{this.props.title}</Header> <Content dangerouslySetInnerHTML={{__html: this.props.content}}> </Content> </DetailWrapper> ) } componentDidMount () { this.props.getDetail(this.props.match.params.id) } } const mapState = (state) => ({ title: state.getIn(['detail', 'title']), content: state.getIn(['detail', 'content']) }) const mapDispatch = (dispatch) => ({ getDetail (id) { dispatch(actionCreators.getDetail(id)) } }) export default connect(mapState, mapDispatch)(withRouter(Detail));
App.js文件:
import { Globalstyle } from './style.js'; import { Provider } from 'react-redux' import { BrowserRouter, Route } from 'react-router-dom' import Header from './common/header/index' import Home from './pages/home/index' // import Detail from './pages/detail/index' // 使用loadablel加载异步组件 import Detail from './pages/detail/lodable' import Login from './pages/login/index' import Write from './pages/write/index' import store from './store/index.js'; function App() { return ( <div className="App"> <Globalstyle /> <Provider store={store}> {/* 这样Provider包裹的组件都有能力使用store了 */} <div style={{marginBottom: 50}}> <BrowserRouter> <Header></Header> <Route path='/login' exact component={Login}></Route> <Route path='/' exact component={Home}></Route> <Route path='/detail/:id' exact component={Detail}></Route> <Route path='/write' exact component={Write}></Route> </BrowserRouter> </div> </Provider> </div> ); } export default App;
记录自己的采坑之路,需要时方便查找