1. 程式人生 > >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