react-router4 实现按需加载并利用withRouter传递props

来源:互联网 发布:联通数据关闭还走流量 编辑:程序博客网 时间:2024/05/16 17:46

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

参考 https://juejin.im/post/58f9717e44d9040069d06cd6

1 0
原创粉丝点击