React 筆記
環(huán)境介紹:
- Webpack: 3.2.0
- React: 15.6.1
配置文件:
package.json
一、說(shuō)明
- 項(xiàng)目采用SASS
- Material-UI 進(jìn)行UI控件插件
- 采用HashRouter 路由進(jìn)行路由管控
二陵刹、易錯(cuò)點(diǎn)
- ES6 中返回的之組件類中必須要一個(gè)公開(kāi)類
export default class 類
然后在引用的時(shí)候
import 類 from "../路徑";
二莲祸、基礎(chǔ)知識(shí)
三、異步加載路由
1)導(dǎo)入必須的組件 react-router-dom
import {
HashRouter as Router,
Route,
Redirect
} from 'react-router-dom'
2)使用路由
??我發(fā)現(xiàn)React 的路由是從上到下依次執(zhí)行的
<Route exact path="/"/>
<!-- 重定向 -->
<Redirect to="/login"/>
<Route path="/login" render={() => (
<Bundle
load={require("bundle-loader!./login.component/login.component")}>
</Bundle>)}/>
<Route path="/index" render={() => (
<Bundle
load={require("bundle-loader!./index.component/index.component")}>
</Bundle>)}/>
Bundle 是什么?
require?
bundle-loader!?
React 15.6 的版本里面對(duì)路由也進(jìn)行了一個(gè)新的定義, 很多地方都是老舊的配置, 因此我在找到了一個(gè)官網(wǎng)地址
reacttraining.com 在里面進(jìn)行了說(shuō)明
?bundle-loader 是一個(gè)webpack 的插件專門用于 拆分代碼 , 返回一個(gè)異步加載對(duì)象, 里面包含了加載對(duì)象的信息.
?require 大家都知道吧, 簡(jiǎn)單概述就是加載JS 使用的方法
Bundle 代碼
/*
* 異步渲染組件
*/
class Bundle extends React.Component {
componentWillMount() {
this.setState({
name: '河馬筆記'
});
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 != null) {
return this.state.mod.prototype.render();
}
return this.state.mod;
}
}
回過(guò)頭來(lái)在看Bundle 組件的內(nèi)部,內(nèi)部構(gòu)造很簡(jiǎn)單嫌蚤。首先看
render
方法,用戶渲染一個(gè)組件断傲,而 mod 對(duì)象是NULL 則返回NULL, 然后當(dāng)程序執(zhí)行了load
方法脱吱,傳進(jìn)來(lái)的是一個(gè)bundle-loader
對(duì)象,這個(gè)對(duì)象loader對(duì)象有一個(gè) load 方法進(jìn)行加載異步加載JS 然后回調(diào)傳入的函數(shù)认罩。mod: mod.default ? mod.default : mod
將值賦值給了React 組件的 State 下的mod 則這個(gè)時(shí)候React 發(fā)現(xiàn)mod 值發(fā)生了變化然后就重新渲染箱蝠。