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

前端之家收集整理的这篇文章主要介绍了react-router4 实现按需加载并利用withRouter传递props前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

猜你在找的React相关文章