----------------------react----------------------
干嘛的:前端框架,把用戶界面抽象成一個(gè)個(gè)的組件,按需組合成頁面
官網(wǎng):https://reactjs.org/
http://react.css88.com/
不同點(diǎn):
angularJs vue react angularTS
控制器 √ 1.x - - 2.x +
過濾器 √ √ - √
指令 √ √ - √
組件 - 組件 組件 √
模板 √ √ - √
引擎 表達(dá)式
共同點(diǎn):
虛擬DOM(angularJs除外 angular有),數(shù)據(jù)驅(qū)動(dòng)
JSX:js + jsx 類XML語法
oo.js/ oo.jsx 合法的
語法要求:
標(biāo)簽要閉合
元素必須要有一個(gè)頂層元素
變量首字母大寫代表組件,小寫是變量
html屬性,小駝峰命名 tabindex -> tabIndex
精髓:多組件組合,jsx+函數(shù)式編程(運(yùn)算寫成一系列的函數(shù)嵌套)
let 變量 = jsx元素 <div><aa></aa></div>
環(huán)境搭建:
a) webpack + webpack-dev-server
/ 指向 index所在位置,圖片,數(shù)據(jù) 都指向 /
js / css / jsx 相對(duì)定位
b) npm install create-react-app -g 官方腳手架
create-react-app 目錄名| .
yarn start 開發(fā)模式
yarn build 打包
更改默認(rèn)的端口號(hào):
1. node_modules\react-scripts\scripts
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3001;
2. npm run eject / yarn eject
修改script/start.js
本地資源導(dǎo)入(import) 不可以導(dǎo)入src之外的包
問題: jsx前景圖片, ./ 和 / 都指向了 public目錄
解決:1.模塊化導(dǎo)入 src目錄里 要在jsx里src的圖片
2.相對(duì)或者絕對(duì)導(dǎo)入public目錄下的圖片
去除eslint 警告:
npm run eject
找到項(xiàng)目下config/webpack.config.dev|prod
注釋關(guān)于eslint的導(dǎo)入和rules規(guī)則
打包 + 預(yù)覽:
npm run build / yarn build
serve -s build --port 端口 --open
serve 服務(wù)器命令行工具(npm i serve -g)
public目錄里面的資源會(huì)直接copy到build目錄,src里面的資源會(huì)打包模塊化
help: https://github.com/facebook/create-react-app
解決方案:
項(xiàng)目資源,盡量從src目錄下引入,打包時(shí)會(huì)模塊化
圖片資源模塊化引入,如何來自庫只能放到public目錄下
c) yeomen 目錄 需要安裝
npm install
npm run dev
ES6 創(chuàng)建組件:
import React from 'react';
class 組件名 extends React.Component{
constrctor(props){ //組件有狀態(tài),需要處理props constrctor就出現(xiàn)
super(props) //類如果有繼承 super就要出現(xiàn)
需要在組件構(gòu)造器內(nèi)處理傳遞過來的props時(shí),props參數(shù)就出現(xiàn)
this.state={ // 本地狀態(tài)
}
}
render(){
return html|jsx
}
方法1(){} 自定義的方法
方法2(){}
}
ES5 創(chuàng)建組件:
var React = require('react');
let 組件名 = React.createClass({
getInitialState:function(){ //組件狀態(tài)
return {
數(shù)據(jù):值
}
}
render:function(){
return html|jsx
}
});
使用組件:
<HelloWorld/>
<HelloWorld></HelloWorld>
渲染(描畫)頁面
import ReactDom from 'react-dom';
var RactDom = require('react-dom');
ReactDom.render(組件/jsx,插入點(diǎn))
組件屬性(props):
調(diào)用組件:<組件名 屬性名=值 屬性名2=值2 .. /> 傳遞屬性
組件內(nèi)部: {this.props.屬性名} jsx表達(dá)式 使用屬性
this 代表的是組件本身
值類型:字符||{表達(dá)式}
this.props.屬性名==array 需要循環(huán)
arr值:this.props.屬性名.map(function(){
return html
})
json {json} 報(bào)錯(cuò), 對(duì)象無法直接通過{obj}展示->{obj.key}
事件:駝峰命名 es6 事件函數(shù)內(nèi)部this會(huì)丟失
<元素 onClick={this.方法}
修正this的指向
onClick={this.方法.bind(null,值)}
onClick={()=>{this.方法()}}
this.方法=this.方法.bind(this)
方法(ev) ev 代理事件對(duì)象 ev.target 返回虛擬dom √
refs: 獲取jsx元素 獲取的是真實(shí)dom
給jsx元素 綁定
<jsx元素
<div
<input
<Header ref="名字"
this.refs.名字
訪問的是 真實(shí)DOM
給jsx元素 設(shè)置ref屬性=名字
this.refs.名字
何時(shí)用:
處理focus、文本選擇或者媒體播放
觸發(fā)強(qiáng)制動(dòng)畫
集成第三方DOM庫
組件之間數(shù)據(jù)傳遞(props傳遞)
父到子 props 傳遞 <Child 屬性=數(shù)據(jù)/>
子到父 props 傳遞 <Child 屬性=父方法/>
{this.props.屬性.bind(this,xx)}
所有 React 組件都必須是純函數(shù),并禁止修改其自身 props
受控元素 :
react 默認(rèn)是單項(xiàng)綁定 defaultValue
value={this.state.數(shù)據(jù)名} model->view
onChange={this.監(jiān)聽方法} view->model( setState )
監(jiān)聽方法: this.setState(...)
處理多個(gè)輸入元素
可以為每個(gè)元素添加一個(gè) name 屬性(通常和數(shù)據(jù)名一致)
處理函數(shù)根據(jù) event.target.name 的值來選擇要做什么
name="inputUserName" name="inputContent"
this.setState({[ev.target.name]:ev.target.value})
react 處理 樣式:
1) 在index.html/index.js : 引入 link/style 場(chǎng)景:應(yīng)用的公共樣式
2)在組件里面引入: import './css/xx.css' 是全局 注入口(程序) 公共樣式
問題: 選擇器沖突,
解決:
a) 命名空間
b) 模塊化: import 變量 from './css/xx.css' 模塊 使用?
webpack配置 "style-loader!css-loader?modules"
<xx className={變量.類名}
jsx:
className="類名 類名2" className={返回字符}
style={{key:value,key:value}}
css3 動(dòng)畫 / ant.desing animation
create-react-app 腳手架資源默認(rèn)配置
本地資源導(dǎo)入(import) 不可以導(dǎo)入src之外的包
jsx前景圖片, ./ 和 / 都指向了 public目錄
import 引入的css,內(nèi)部的資源url
./ 指向 src
/ 指向 public
生命周期流程:
實(shí)例化 -> 更新期 -> 銷毀時(shí)
實(shí)例化:
es5:
1.取得默認(rèn)屬性(getDefaultProps) 外部傳入的props
2.初始狀態(tài)(getInitailState) state狀態(tài)
3.即將掛載 componentWillMount
4.描畫VDOM render
5.掛載完畢 componentDidMount
es6:
1.取得默認(rèn)屬性(getDefaultProps) 外部傳入的props
2.初始狀態(tài)(getInitailState) state狀態(tài)
1 && 2 都在構(gòu)造器里面完成
constructor(props){
super(props) == getDefaultProps
this.state={} == getInitailState
}
3.即將掛載 componentWillMount
4.描畫DOM render
5.掛載完畢 componentDidMount
更新期:
1.是否更新 shouldComponentUpdate 指視圖
2.即將更新 componentWillUpdate
3.描畫vdom render
4.描畫結(jié)束 componentDidUpdate
銷毀時(shí):
即將卸載 componentWillUnmount
實(shí)例化->存在(更新)->銷毀時(shí)
getDefaultProps->getInitialState->componentWillMount->render->componentDidMount
->shouldComponentUpdate->componentWillUpdate->render->componentDidUpdate->
->componentWillUnmount
數(shù)據(jù)交互:
官方腳手架 靜態(tài)數(shù)據(jù)讀取時(shí),參考根指向public '/data' == public/data
fetch 原生就有
fetch(url+數(shù)據(jù),{配置}).then(成功函數(shù)(res))
res.ok -> true/false 成功/失敗
res.status - > 狀態(tài)碼
res.body 數(shù)據(jù) 數(shù)據(jù)流(stream)
res.text() 轉(zhuǎn)換 文本(string)
過程異步: return res.text()
同步: res.text().then((data)=>{}) data:轉(zhuǎn)換后的數(shù)據(jù)
res.json() 轉(zhuǎn) 對(duì)象
配置:
method:'POST'
headers:{"Content-type":"application/x-www-form-urlencoded"},
body:'a=1&b=2'|{a:1,b:2}
jsonp: fetch不帶jsonp請(qǐng)求 需要依賴第三庫
npm install fetch-jsonp -D
import xxx from 'xxx'
用法:
fetchJsonp(url+數(shù)據(jù),{配置}).then(success(res)).catch(error)
特點(diǎn): 是個(gè)promise 返回promise 數(shù)據(jù)是個(gè)流
解析:res.json() -> 流轉(zhuǎn)換數(shù)據(jù) 是異步
配置:
timeout: 延時(shí) 5000
jsonpCallback: 回調(diào)函數(shù)key callback
jsonpCallbackFunction: null
無狀態(tài)(沒有state)組件(簡(jiǎn)寫)創(chuàng)建:
const 組件名=(props)=>(jsx)
const 組件名=props=>jsx
const 組件名=(props)=>{
let xx=props.xx
return html
}
無狀態(tài)組件特點(diǎn):
不能訪問this對(duì)象(this.ref,this.state ... )
只能訪問props
無需實(shí)例化,渲染性能高
this.方法/鉤子(生命周期) 也不需要
react路由 4.x
資料:
API:https://reacttraining.com/react-router/web/guides/quick-start
CN:http://blog.csdn.net/sinat_17775997/article/details/77411324
redux:https://github.com/reacttraining/react-router/tree/master/packages/react-router-redux
區(qū)別:
V4
嵌套式路由(路由配置在組件內(nèi)部),動(dòng)態(tài)路由,包容性(多路由渲染)
舍去了路由鉤子
V3
分離式(統(tǒng)一位置配置),靜態(tài)路由,排他性(只有一個(gè)路由被渲染)
理念:
遵循Just Component的 API 設(shè)計(jì)理念 萬物皆組件,路由規(guī)則位于布局和 UI 本身之間
安裝引入 react-router-dom
React Router被拆分成三個(gè)包:react-router,react-router-dom和react-router-native。react-router提供核心的路由組件與函數(shù)。其余兩個(gè)則提供運(yùn)行環(huán)境(即瀏覽器與react-native)所需的特定組件
BrowserRouter 使用 HTML5 提供的 history API 來保持 UI 和 URL 的同步
HashRouter 使用 URL 的 hash (例如:window.location.hash) 來保持 UI 和URL 的同步
結(jié)構(gòu):
BrowserRouter|HashRouter 路由對(duì)象
根組件(App)|其他組件
NavLink|Link 導(dǎo)航
Route 匹配+展示
Redirect 跳轉(zhuǎn)
404 <Redirect to="/error"/>
默認(rèn)路由 <Route exact path={match.path} render={fuc}
Route 屬性
path(string): 路由匹配路徑。(沒有path屬性的Route 總是會(huì) 匹配);
exact(bool):
為true時(shí),要求全路徑匹配(/home)。V4 的路由默認(rèn)為“包含”的(/和/home都匹配),這意味著多個(gè) <Route> 可以同時(shí)進(jìn)行匹配和渲染
component:在地址匹配的時(shí)候React的組件才會(huì)被渲染,route props也會(huì)隨著一起被渲染
render:這種方式對(duì)于內(nèi)聯(lián)渲染和包裝組件卻不引起意料之外的重新掛載特別方便
Link:
to:string/object:要跳轉(zhuǎn)的路徑或地址;
NavLink:是<Link> 的一個(gè)特定版本
activeClassName(string):設(shè)置選中樣式,默認(rèn)值為 active;
activeStyle(object):當(dāng)元素被選中時(shí), 為此元素添加樣式;
Switch:該組件用來渲染匹配地址的第一個(gè)<Route>或者<Redirect>,僅渲染一個(gè)路由,排他性路由,默認(rèn)全匹配(場(chǎng)景:側(cè)邊欄和面包屑,引導(dǎo)選項(xiàng)卡等
Redirect:
<Redirect from='/' to='/home'/> 總是會(huì)被重定向
404: <Route component={Error}/> 總是會(huì)匹配
參數(shù)數(shù)據(jù):{history,location,match}==props
傳遞:
to={match.url+'/001'}
to={`${match.url}/002?a=1&b=2`}
to={{pathname:match.url+'/003',search:'?a=11&b=12',hash:'#a1'}}
<Route path={match.path+'/:aid'} component={Detail}
注意:
url - (瀏覽器 URL 中的實(shí)際路徑) URL 匹配的部分。 用于構(gòu)建嵌套的 <Link>
path - (路由編寫的路徑) 用于匹配路徑模式。用于構(gòu)建嵌套的 <Route>
接收:
接參數(shù):{match.params.aid}
接數(shù)據(jù):{location.search}
接地址:{location.pathname}
注意:
無法從v4 中獲取 URL 的查詢字符串了。因?yàn)闆]有關(guān)于如何處理復(fù)雜查詢字符串的標(biāo)準(zhǔn)。所以,作者讓開發(fā)者去選擇如何處理查詢字符串。推薦query-string庫
跳轉(zhuǎn):
history.push('/user?a=1&b=2')
history.push({pathname:'/user',search:'?a=11&b=22'})
history.replace({pathname:'/user',search:'?a=111&b=222'})
history.go(-1)
授權(quán)路由:自定義路由
前置守衛(wèi)
<AuthRoute path="/user" component={User}/>
AuthRoute==授權(quán)路由==react組件==自定義路由
條件:返回一個(gè)Route 組件
Route的render函數(shù)內(nèi)部判斷加載目標(biāo)||Redirect組件
實(shí)現(xiàn):
AuthRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props =>
Math.random()<0.5 ?
<Component {...props} />
: <Redirect to="/login" />
}
/>
)
目標(biāo)組件 Component == User
延展剩余屬性 rest
路由信息 ...props User組件需要用到的路由信息
數(shù)據(jù)預(yù)載:
AuthRoute 組件構(gòu)造器存狀態(tài)和預(yù)載數(shù)據(jù)
DidMount鉤子里異步請(qǐng)求,獲取狀態(tài)和數(shù)據(jù)
fetch(url).then(result=>this.setState({}))
render鉤子返回 Route
<Route {...rest} render={props => Xxx?<Component data={預(yù)載數(shù)據(jù)}
if(!this.state.hasAuthed) return null;初始渲染時(shí),未發(fā)送認(rèn)證請(qǐng)求,因此不渲染
Prompt:后置守衛(wèi),離開后守衛(wèi)
import { Prompt } from 'react-router-dom'
<Prompt
when={this.state.isBlocking}
message={location=>{return `未保存,是否去向${location.pathname}`}}
/>
message: 后面可以跟簡(jiǎn)單的提示語,也可以跟函數(shù),函數(shù)是有默認(rèn)參數(shù)的。
when: when的屬性值為true時(shí)防止跳轉(zhuǎn);
問題:子路由使用父路由的展示區(qū)(插槽)
<Route path="/a" render={()=>
<div>
<Switch>
<Route path="/a/b" component={b}
<Route path="/a/c" component={c}
<Route path="/a" component={a}
</Switch>
</div>
>
思想:
組件拆分目標(biāo):為了復(fù)用
組件如何拆:?jiǎn)我辉瓌t
狀態(tài)應(yīng)該給誰:
盡量給頂層組件(狀態(tài)提升),->props->子組件
可以從 props(屬性) 或者 state(狀態(tài)) 得到,那么它可能不應(yīng)該在 當(dāng)前state(狀態(tài)) 中
方法-》操作數(shù)據(jù)(數(shù)據(jù)|狀態(tài)在哪,方法就應(yīng)該在哪)
props取名:從組件本身的角度來命名, 而不是它被使用的上下文環(huán)境
純函數(shù):不會(huì)試圖改變它們的輸入,并且對(duì)于同樣的輸入,始終可以得到相同的結(jié)果,React
組件都必須是純函數(shù),并禁止修改其自身 props
function(a,b){不會(huì)隨機(jī),不會(huì)修改a和b的值,輸出可控}
setState: 是異步的,會(huì)將多個(gè) setState() 調(diào)用合并為一次更新,所以不能同步依賴上一個(gè)setState的值,作為下一個(gè)setState的參數(shù)
解決:
1) this.setState(function(prevState,props){})
prevState 抓取之前this.setState的所有狀態(tài)
props 所有屬性
更新會(huì)被合并,淺合并
2) 函數(shù)節(jié)流(異步操作)
3) ev.target......
組件傳值|通訊|流動(dòng)|流向:
1) 子A->父->子B props
2) 父方法(){this.refs.子.方法}
3) pub/sub模式 消息通知(觀察者模式) npm install npm install pubsub-js -D
import PubSub from 'pubsub-js'
訂閱: token=PubSub.subscribe('消息名',回調(diào)函數(shù)('消息名',數(shù)據(jù)))
發(fā)布: PubSub.publish('消息名',數(shù)據(jù))
清除指定訂閱:PubSub.unsubscribe(token);
清除所有:PubSub.unsubscribeAll()
注意:訂閱方不存在了,相關(guān)的訂閱注意清除
先訂閱,后發(fā)布
4) 狀態(tài)管理(redux)
5) cookie localstorage
6) 路由
狀態(tài)管理
flux(思想) vue實(shí)現(xiàn)(vuex) react實(shí)現(xiàn)(redux + react-redux)
狀態(tài)管理(redux):可以同一個(gè)地方查詢狀態(tài),改變狀態(tài),傳播狀態(tài)
何時(shí)用:中大項(xiàng)目,組件狀態(tài)需要共享,在任何地方都可以拿到,組件需要改變?nèi)? 局狀態(tài),一個(gè)組件需要改變另外一個(gè)組件的狀態(tài)
思維:
在應(yīng)用頂層創(chuàng)建store(狀態(tài))對(duì)象,其他底層組件共享這個(gè)store(狀態(tài))
數(shù)據(jù)流動(dòng):
component->action->reducer->state<-component
component: 展示結(jié)果(含處理結(jié)果代碼)
action: 動(dòng)作轉(zhuǎn)發(fā),異步請(qǐng)求,
reducer: 業(yè)務(wù)處理邏輯,返回(return)新state
state: 狀態(tài)收集,更新內(nèi)部state狀態(tài),更新訂閱(store.subscribe)state的組件(component)
通過store.dispatch發(fā)送 給 reducer
在組件內(nèi)部 通過 this.props.store.getState() 抓state狀態(tài) 特點(diǎn) 只抓一次
this.props.store.subscribe() 訂閱 數(shù)據(jù)更新,會(huì)觸發(fā)
getState放在subscribe內(nèi)部
操作流程:
1. {createStore} from 'redux'
2. 生成默認(rèn)state defaultState={}
3. 創(chuàng)建reducer
const reducer = (state=defaultState,action)=>{
let {type,payload}=action
swtich type
case XXXXX
更新copy后的state Object.assign(空,老,新)
default:
return state
}
4. 創(chuàng)建store對(duì)象
store = createStore(reducer,state)
5. store傳遞給組件
<組件名 store={store}/>
6. 更新,狀態(tài)獲取
組件內(nèi)部: this.props.store== store
this.props.store.dispatch({type:xxx,payload:ooo}) 發(fā)送action給reducer
this.props.store.subscribe(回調(diào)) 訂閱 state 更新state時(shí)觸發(fā)
this.props.store.getState() 獲取狀態(tài),執(zhí)行一次
react-redux
基于redux思想,專門為react而生
思想: 容器組件, UI組件
App: 拿到store,修改、獲取store
store:外面
UI組件:
負(fù)責(zé)UI呈現(xiàn),不帶任何業(yè)務(wù)邏輯
沒有狀態(tài)(不使用this 沒有state)
所有的數(shù)據(jù)有props提供
不使用任何redux的API
容器組件:
index.js:
import {Provider,connect} from react-redux
<Provider store={store}>
<容器組件/>
</Provider>
- 項(xiàng)目分析,組件安排
|-config
|-webpack.config.js
|-script
|-public
|- data
|- 數(shù)據(jù)
|- index.html
|-node_modules
|-src
|- components
|- App
|- NavBar / FootBar
|- Home / Follow / Column / User
|- Article / Login / Reg
|- Slider / Error / List
|- common(filters)
|- date.js / fillzero.js/...
|- assets
|- css
|- img
|- js
|- store
|- ..
Index.js
package.json
- 布局(切圖,mint-ui,elementUI...ant.design),模板移植
樣式:全局引入
src / import
-
路由搭建 route4
樣式?jīng)_突(命名沖突(錯(cuò)開))
import 模塊名 from '../css/xx.css'模塊名.類名
-
數(shù)據(jù)交互
fetch(url,{配置}).then().catch()home->newlist dataName="home" listData={this.state.listData}
follow->newlist dataName="follow" listData={this.state.listData}
↓
newlist -》link pathname:'detail/'+item.id,
query:{dataName:dataName}
↓
detail this.props.router.location.query.dataName 全局方法(過濾事件,補(bǔ)零)
|-common
date.js
fillzero.js
...
index.js
import date/fillzero ..
export {
date,fillzero
}
-
非狀態(tài)管理,控制navbar / footbar / loading
this.props.router.location.pathname -> navbar / footbar
6.5 全局loading
pubsub [App訂閱, home/follow/.. 發(fā)布]
問題:用戶速度切換,this.setState報(bào)錯(cuò)
分析:fetch中斷--無法中斷/isMounted屬性(es5)/狀態(tài)控制(組件卸載了,狀態(tài)和事件都沒了)
解決:高光盒(lightBox)√ / 自個(gè)維護(hù)一個(gè)組件屬性 this.自定義屬性
-
同級(jí)組件傳值思路:
a) 子A->父->子B
父方法(){this.refs.子.方法}
b) pub/sub模式 消息通知(觀察者模式) npm install npm install pubsub-js -D
var pubsub = new PubSub();
訂閱: onUserAdd=pubsub.subscribe('消息名',回調(diào)函數(shù)(數(shù)據(jù),'消息名'))
發(fā)布: pubsub.publish('消息名',數(shù)據(jù))
清除指定訂閱:pubsub.unsubscribe(onUserAdd);
清除所有:pubsub.unsubscribeAll()注意:發(fā)布方不存在了,相關(guān)的訂閱注意清除
c) 狀態(tài)管理(redux)
中間件/路由守衛(wèi)/路由懶加載/前后端分離/ant.design .......
路由懶加載:
異步組件:create-react-app 環(huán)境 webpack自動(dòng)分片打包
方式1 import ("./ChildB.js").then(
ChildB=>console.log(ChildB)
)
方式2 const Child = asyncComponent(()=>import("./Child"))
export default function asyncComponent(importComponent) {
class AsyncComponent extends Component {
constructor(props) {
super(props);
this.state = {
component: null
};
}
async componentDidMount() {
const { default: component } = await importComponent();
this.setState({
component: component
});
}
render() {
const C = this.state.component;
return C ? <C {...this.props} /> : null;
}
}
return AsyncComponent;
}
方式3
import Loadable from 'react-loadable';
const Loading = () => <div>Loading...</div>;
const Home = Loadable({
loader: () => import('./routes/Home'),
loading: Loading,
loading:()=>{return null}
});
路由 <Route path=.. component={Home}/> 路由懶加載
前后端分離:
前端:fetch 請(qǐng)求頭里面帶憑證,帶cookie
fetch('http:localhost:3000/cookies', {
credentials: 'include', //憑證
method:'get',
headers:{
'Accept':'application/json,text/plain,/',
'Content-type':'application/x-www-form-urlencoded;charset=utf-8'
},
body:數(shù)據(jù)
}).then(function(res) {
// ...
})