bundle.jsx
import React,{Component} from 'react'
export default class Bundle extends Component {
componentWillMount() {
this.load(this.props)
}
componentWillReceiveProps(nextProps) {
if (nextProps.load !== this.props.load) {
this.load(nextProps)
}
}
load(props) {
this.setState({mod: null})
props.load((mod) => {
this.setState({
mod: mod.default
? mod.default
: mod
})
})
}
render() {
if (!this.state.mod)
return false
return this.props.children(this.state.mod)
}
}
// app.jsx
// bundle模型用来异步加载组件
import Bundle from './bundle.jsx';
// 引入单个页面(包括嵌套的子页面)
// 同步引入
import Index from './app/index.js';
// 异步引入
import ListContainer from 'bundle-loader?lazy&name=app-[List]!../pages/List';
const List = () => (
<Bundle load={ListContainer}>
{(List) => <List />}
</Bundle>
)
// ...
<HashRouter>
<Router basename="/">
<div>
<Route exact path="/" component={Index} />
<Route path="/list" component={List} />
</div>
</Router>
</HashRouter>
// ...
webpack.config.js-output
chunkFilename: '[name]-[id].[chunkhash:8].bundle.js'
问题
无法传递this.props,如this.props.params,location
解决
react-router
自带的withRouter
可轻松解决:
import { withRouter } from 'react-router'
class Test extends Component {
...
render(){
const { match,location,history } = this.props
...
}
}
export default withRouter(Test)
//export default withRouter(connect(...)(Test))//with redux