react-router4 实现按需加载并利用withRouter传递props
发布时间:2020-12-15 07:22:17 所属栏目:百科 来源:网络整理
导读: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
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>
// ...
问题
解决
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
参考 https://juejin.im/post/58f9717e44d9040069d06cd6 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |