react-router4 实现按需加载 实现按需加载后 引起 没法获取 this
发布时间:2020-12-15 07:19:48 所属栏目:百科 来源:网络整理
导读:react-router4 实现按需加载 实现按需加载后 引起 没法获取 his.props,如this.props.params,location 的问题解决办法 实现按需加载的办法 首先,新建一个bundle.js文件:import React,{ Component } from 'react'export default class Bundle extends React.
react-router4 实现按需加载实现按需加载后 引起 没法获取 his.props,如this.props.params,location 的问题解决办法
首先,新建一个bundle.js文件: import React,{ Component } from 'react' export default class Bundle extends React.Component { state = { // short for "module" but that's a keyword in js,so "mod" mod: null } 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({ // handle both es imports and cjs mod: mod.default ? mod.default : mod }) }) } render() { if (!this.state.mod) return false return this.props.children(this.state.mod) } } 然后,在入口处使用按需加载: // ... // bundle模型用来异步加载组件 import Bundle from './bundle.js'; // 引入单个页面(包括嵌套的子页面) // 同步引入 import Index from './app/index.js'; // 异步引入 import ListContainer from 'bundle-loader?lazy&name=app-[name]!./app/list.js'; 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: { path: path.resolve(__dirname,'./output'),filename: '[name].[chunkhash:8].bundle.js',chunkFilename: '[name]-[id].[chunkhash:8].bundle.js',}``` 2. 解决 this.props 获取不到参数的问题 import { withRouter } from 'react-router' class Test extends Component { ... render(){ const { match,location,history } = this.props ... } } export default withRouter(Test) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |