摘要: 很多值得了解的细节。
fundebug经授权转载,版权归原作者所有。
react 起源于 facebook 的内部项目,因为该公司对市场上所有 javascript mvc 框架,都不满意,就决定自己写一套,用来架设 instagram 的网站。做出来以后,发现这套东西很好用,就在2013年5月开源了。
diff算法
和 虚拟dom
实现视图的高效更新> jsx --to--> everything - jsx --> html - jsx --> native ios或android中的组件(xml) - jsx --> vr - jsx --> 物联网
组件化
开发方式,符合现代web开发的趋势react将dom抽象为虚拟dom,虚拟dom其实就是用一个对象来描述dom,通过对比前后两个对象的差异,最终只把变化的部分重新渲染,提高渲染的效率
为什么用虚拟dom,当dom反生更改时需要遍历 而原生dom可遍历属性多大231个 且大部分与渲染无关 更新页面代价太大
vituraldom的处理方式
当你使用react的时候,在某个时间点 render() 函数创建了一棵react元素树,
在下一个state或者props更新的时候,render() 函数将创建一棵新的react元素树,
react将对比这两棵树的不同之处,计算出如何高效的更新ui(只更新变化的地方)
有一些解决将一棵树转换为另一棵树的最小操作数算法问题的通用方案。然而,树中元素个数为n,最先进的算法 的时间复杂度为o(n3) 。
如果直接使用这个算法,在react中展示1000个元素则需要进行10亿次的比较。这操作太过昂贵,相反,react基于两点假设,实现了一个o(n)算法,提升性能:
react中有两种假定:
// 旧树 <div> <counter /> </div> // 新树 <span> <counter /> </span> 执行过程:destory counter -> insert counter
// 旧 <div classname="before" title="stuff" /> // 新 <div classname="after" title="stuff" /> 只更新:classname 属性 // 旧 <div style={{color: 'red', fontweight: 'bold'}} /> // 新 <div style={{color: 'green', fontweight: 'bold'}} /> 只更新:color属性
// 旧 <ul> <li>first</li> <li>second</li> </ul> // 新 <ul> <li>first</li> <li>second</li> <li>third</li> </ul> 执行过程: react会匹配新旧两个<li>first</li>,匹配两个<li>second</li>,然后添加 <li>third</li> tree
// 旧 <ul> <li>duke</li> <li>villanova</li> </ul> // 新 <ul> <li>connecticut</li> <li>duke</li> <li>villanova</li> </ul> 在没有key属性时执行过程: react将改变每一个子删除重新创建,而非保持 <li>duke</li> 和 <li>villanova</li> 不变
为了解决以上问题,react提供了一个 key 属性。当子节点带有key属性,react会通过key来匹配原始树和后来的树。
// 旧 <ul> <li key="2015">duke</li> <li key="2016">villanova</li> </ul> // 新 <ul> <li key="2014">connecticut</li> <li key="2015">duke</li> <li key="2016">villanova</li> </ul> 执行过程: 现在 react 知道带有key '2014' 的元素是新的,对于 '2015' 和 '2016' 仅仅移动位置即可
<li key={item.id}>{item.name}</li>
npm i -s react react-dom
react
:react 是react库的入口点react-dom
:提供了针对dom的方法,比如:把创建的虚拟dom,渲染到页面上// 1. 导入 react import react from 'react' import reactdom from 'react-dom' // 2. 创建 虚拟dom // 参数1:元素名称 参数2:元素属性对象(null表示无) 参数3:当前元素的子元素string||createelement() 的返回值 const divvd = react.createelement('div', { title: 'hello react' }, 'hello react!!!') // 3. 渲染 // 参数1:虚拟dom对象 参数2:dom对象表示渲染到哪个元素内 参数3:回调函数 reactdom.render(divvd, document.getelementbyid('app'))
createelement()
方式,代码编写不友好,太复杂var dv = react.createelement( "div", { classname: "shopping-list" }, react.createelement( "h1", null, "shopping list for " ), react.createelement( "ul", null, react.createelement( "li", null, "instagram" ), react.createelement( "li", null, "whatsapp" ) ) ) // 渲染 reactdom.render(dv, document.getelementbyid('app'))
npm i -d babel-preset-react
(依赖与:babel-core/babel-loader)注意:jsx的语法需要通过 babel-preset-react 编译后,才能被解析执行
/* 1 在 .babelrc 开启babel对 jsx 的转换 */ { "presets": [ "env", "react" ] } /* 2 webpack.config.js */ module: [ rules: [ { test: /\.js$/, use: 'babel-loader', exclude: /node_modules/ }, ] ] /* 3 在 js 文件中 使用 jsx */ const dv = ( <div title="标题" classname="cls container">hello jsx!</div> ) /* 4 渲染 jsx 到页面中 */ reactdom.render(dv, document.getelementbyid('app'))
classname
代替 class
htmlfor
代替{/* 中间是注释的内容 */}
react 组件可以让你把ui分割为独立、可复用的片段,并将每一片段视为相互独立的部分。
props
),并且返回一个react对象,用来描述展示在页面中的内容函数式组件 和 class 组件的使用场景说明:
null
()
包裹,避免换行问题function welcome(props) { return ( // 此处注释的写法 <div classname="shopping-list"> {/* 此处 注释的写法 必须要{}包裹 */} <h1>shopping list for {props.name}</h1> <ul> <li>instagram</li> <li>whatsapp</li> </ul> </div> ) } reactdom.render( <welcome name="jack" />, document.getelementbyid('app') )
在es6中class仅仅是一个语法糖,不是真正的类,本质上还是构造函数+原型 实现继承
// es6中class关键字的简单使用 // - **es6中的所有的代码都是运行在严格模式中的** // - 1 它是用来定义类的,是es6中实现面向对象编程的新方式 // - 2 使用`static`关键字定义静态属性 // - 3 使用`constructor`构造函数,创建实例属性 // - [参考](http://es6.ruanyifeng.com/#docs/class) // 语法: class person { // 实例的构造函数 constructor constructor(age){ // 实例属性 this.age = age } // 在class中定义方法 此处为实例方法 通过实例打点调用 sayhello () { console.log('大家好,我今年' + this.age + '了'); } // 静态方法 通过构造函数打点调用 person.doudou() static doudou () { console.log('我是小明,我新get了一个技能,会暖床'); } } // 添加静态属性 person.staticname = '静态属性' // 实例化对象 const p = new person(19) // 实现继承的方式 class american extends person { constructor() { // 必须调用super(), super表示父类的构造函数 super() this.skin = 'white' this.eyecolor = 'white' } } // 创建react对象 // 注意:基于 `es6` 中的class,需要配合 `babel` 将代码转化为浏览器识别的es5语法 // 安装:`npm i -d babel-preset-env` // react对象继承字react.component class shoppinglist extends react.component { constructor(props) { super(props) } // class创建的组件中 必须有rander方法 且显示return一个react对象或者null render() { return ( <div classname="shopping-list"> <h1>shopping list for {this.props.name}</h1> <ul> <li>instagram</li> <li>whatsapp</li> </ul> </div> ) } }
推荐大家使用fundebug,一款很好用的bug监控工具~
只读的对象
叫做 props
,无法给props添加属性props
props
对象中的属性function welcome(props){ // props ---> { username: 'zs', age: 20 } return ( <div> <div>welcome react</div> <h3>姓名:{props.username}----年龄是:{props.age}</h3> </div> ) } // 给 hello组件 传递 props:username 和 age(如果你想要传递numb类型是数据 就需要向下面这样) reactdom.reander(<hello username="zs" age={20}></hello>, ......)
// 创建hello2.js组件文件 // 1. 引入react模块 // 由于 jsx 编译后会调用 react.createelement 方法,所以在你的 jsx 代码中必须首先拿到react。 import react from 'react' // 2. 使用function构造函数创建组件 function hello2(props){ return ( <div> <div>这是hello2组件</div> <h1>这是大大的h1标签,我大,我骄傲!!!</h1> <h6>这是小小的h6标签,我小,我傲娇!!!</h6> </div> ) } // 3. 导出组件 export default hello2 // app.js中 使用组件: import hello2 from './components/hello2'
props
props
是只读的,无法给props
添加或修改属性props.children
:获取组件的内容,比如:
<hello>组件内容</hello>
中的 组件内容
// props 是一个包含数据的对象参数,不要试图修改 props 参数 // 返回值:react元素 function welcome(props) { // 返回的 react元素中必须只有一个根元素 return <div>hello, {props.name}</div> } class welcome extends react.component { constructor(props) { super(props) } render() { return <h1>hello, {this.props.name}</h1> } }
状态即数据
组件内部
使用的数据class
创建的组件才具有状态state
中添加 render()
方法中不需要的数据,会影响渲染性能!
render()
方法中调用 setstate() 方法来修改state
的值
this.state.name = 'rose'
方式设置state(不推荐!!!!)// 例: class hello extends react.component { constructor() { // es6继承必须用super调用父类的constructor super() this.state = { gender: 'male' } } render() { return ( <div>性别:{ this.state.gender }</div> ) } }
// 1、jsx const element = ( <h1 classname="greeting"> hello, world! </h1> ) // 2、jsx -> createelement const element = react.createelement( 'h1', {classname: 'greeting'}, 'hello, world!' ) // react elements: 使用对象的形式描述页面结构 // note: 这是简化后的对象结构 const element = { type: 'h1', props: { classname: 'greeting', }, children: ['hello, world'] }
<commentlist></commentlist>
和 <comment></comment>
[ { user: '张三', content: '哈哈,沙发' }, { user: '张三2', content: '哈哈,板凳' }, { user: '张三3', content: '哈哈,凉席' }, { user: '张三4', content: '哈哈,砖头' }, { user: '张三5', content: '哈哈,楼下山炮' } ] // 属性扩展 <comment {...item} key={i}></comment>
// 1. 直接写行内样式: <li style={{border:'1px solid red', fontsize:'12px'}}></li> // 2. 抽离为对象形式 var styleh3 = {color:'blue'} var styleobj = { listyle:{border:'1px solid red', fontsize:'12px'}, h3style:{color:'green'} } <li style={styleobj.listyle}> <h3 style={styleobj.h3style}>评论内容:{props.content}</h3> </li> // 3. 使用样式表定义样式: import '../css/comment.css' <p classname="puser">评论人:{props.user}</p>
组件生命周期函数的定义:从组件被创建,到组件挂载到页面上运行,再到页面关闭组件被卸载,这三个阶段总是伴随着组件各种各样的事件,那么这些事件,统称为组件的生命周期函数!
constructor()
componentwillmount()
render()
componentdidmount()
componentwillreceiveprops()
shouldcomponentupdate()
componentwillupdate()
render()
componentdidupdate()
componentwillunmount()
constructor()
constructor()
的参数props
获取class greeting extends react.component { constructor(props) { // 获取 props super(props) // 初始化 state this.state = { count: props.initcount } } } // 初始化 props // 语法:通过静态属性 defaultprops 来初始化props greeting.defaultprops = { initcount: 0 };
componentwillmount()
同步
地设置状态将不会触发重渲染setstate()
方法来改变状态值componentwillmount() { console.warn(document.getelementbyid('btn')) // null this.setstate({ count: this.state.count + 1 }) }
render()
render()
,render()
又重新改变状态render() { console.warn(document.getelementbyid('btn')) // null return ( <div> <button id="btn" onclick={this.handleadd}>打豆豆一次</button> { this.state.count === 4 ? null : <counterchild initcount={this.state.count}></counterchild> } </div> ) }
componentdidmount()
setstate()
修改状态的值componentdidmount() { // 此时,就可以获取到组件内部的dom对象 console.warn('componentdidmount', document.getelementbyid('btn')) }
props
或者state
改变的时候,都会触发运行阶段的函数componentwillreceiveprops()
props
前触发这个方法props
值this.props
获取到上一次的值this.props
和nextprops
并在该方法中使用this.setstate()
处理状态改变state
不会触发该方法componentwillreceiveprops(nextprops) { console.warn('componentwillreceiveprops', nextprops) }
shouldcomponentupdate()
true
重新渲染,否则不渲染false
,那么,后续render()
方法不会被调用// - 参数: // - 第一个参数:最新属性对象 // - 第二个参数:最新状态对象 shouldcomponentupdate(nextprops, nextstate) { console.warn('shouldcomponentupdate', nextprops, nextstate) return nextstate.count % 2 === 0 }
componentwillupdate()
componentwillupdate(nextprops, nextstate) { console.warn('componentwillupdate', nextprops, nextstate) }
render() 渲染
mounting
阶段的render
是同一个函数componentdidupdate()
componentdidupdate(prevprops, prevstate) { console.warn('componentdidupdate', prevprops, prevstate) }
componentwillunmount()
componentdidmount
创建的dom对象require('create-react-class')
,可以在不适用es6的情况下,创建有状态组件createreactclass()
方式创建组件中的两个函数var createreactclass = require('create-react-class'); var greeting = createreactclass({ // 初始化 props getdefaultprops: function() { console.log('getdefaultprops'); return { title: 'basic counter!!!' } }, // 初始化 state getinitialstate: function() { console.log('getinitialstate'); return { count: 0 } }, render: function() { console.log('render'); return ( <div> <h1>{this.props.title}</h1> <div>{this.state.count}</div> <input type='button' value='+' onclick={this.handleincrement} /> </div> ); }, handleincrement: function() { var newcount = this.state.count + 1; this.setstate({count: newcount}); }, proptypes: { title: react.proptypes.string } }); reactdom.render( react.createelement(greeting), document.getelementbyid('app') );
setstate()
方法修改状态,状态改变后,react会重新渲染组件// 修改state(不推荐使用) // https://facebook.github.io/react/docs/state-and-lifecycle.html#do-not-modify-state-directly this.state.test = '这样方式,不会重新渲染组件'; constructor(props) { super(props) // 正确姿势!!! // -------------- 初始化 state -------------- this.state = { count: props.initcount } } componentwillmount() { // -------------- 修改 state 的值 -------------- // 方式一: this.setstate({ count: this.state.count + 1 }) this.setstate({ count: this.state.count + 1 }, function(){ // 由于 setstate() 是异步操作,所以,如果想立即获取修改后的state // 需要在回调函数中获取 // https://doc.react-china.org/docs/react-component.html#setstate }); // 方式二: this.setstate(function(prevstate, props) { return { counter: prevstate.counter + props.increment } }) // 或者 - 注意: => 后面需要带有小括号,因为返回的是一个对象 this.setstate((prevstate, props) => ({ counter: prevstate.counter + props.increment })) }
推荐大家使用fundebug,一款很好用的bug监控工具~
onclick
绑定ref
获取元素)
ref
是react提供的一个特殊属性ref
的使用说明:onclick
用来绑定单击事件<input type="button" value="触发单击事件" onclick={this.handlecountadd} onmouseenter={this.handlemouseenter} />
ref
属性,然后,获取元素绑定事件// jsx // 将当前dom的引用赋值给 this.txtinput 属性 <input ref={ input => this.txtinput = input } type="button" value="我是豆豆" /> componentdidmount() { // 通过 this.txtinput 属性获取元素绑定事件 this.txtinput.addeventlistener(() => { this.setstate({ count:this.state.count + 1 }) }) }
bind
绑定箭头函数
绑定bind
能够调用函数,改变函数内部this的指向,并返回一个新函数bind
第一个参数为返回函数中this的指向,后面的参数为传给返回函数的参数// 自定义方法: handlebtnclick(arg1, arg2) { this.setstate({ msg: '点击事件修改state的值' + arg1 + arg2 }) } render() { return ( <div> <button onclick={ // 无参数 // this.handlebtnclick.bind(this) // 有参数 this.handlebtnclick.bind(this, 'abc', [1, 2]) }>事件中this的处理</button> <h1>{this.state.msg}</h1> </div> ) }
bind
constructor() { super() this.handlebtnclick = this.handlebtnclick.bind(this) } // render() 方法中: <button onclick={ this.handlebtnclick }>事件中this的处理</button>
箭头函数
中的this由所处的环境决定,自身不绑定this<input type="button" value="在构造函数中绑定this并传参" onclick={ () => { this.handlebtnclick('参数1', '参数2') } } /> handlebtnclick(arg1, arg2) { this.setstate({ msg: '在构造函数中绑定this并传参' + arg1 + arg2 }); }
在html当中,像
input
,textarea
和select
这类表单元素会维持自身状态,并根据用户输入进行更新。
在react中,可变的状态通常保存在组件的state
中,并且只能用setstate()
方法进行更新.
react根据初始状态渲染表单组件,接受用户后续输入,改变表单组件内部的状态。
因此,将那些值由react控制的表单元素称为:受控组件。
// 模拟实现文本框数据的双向绑定 <input type="text" value={this.state.msg} onchange={this.handletextchange}/> // 当文本框内容改变的时候,触发这个事件,重新给state赋值 handletextchange = event => { console.log(event.target.value) this.setstate({ msg: event.target.value }) }
npm i -s prop-types
proptypes
(对象),来约束props
// 引入模块 import proptypes from 'prop-types' // ...以下代码是类的静态属性: // proptypes 静态属性的名称是固定的!!! static proptypes = { initcount: proptypes.number, // 规定属性的类型 initage: proptypes.number.isrequired // 规定属性的类型,且规定为必传字段 }
react中的单向数据流动:
在我们的评论列表案例中:
props
props
proptypes
类型限制来使用class grandfather extends react.component { // 类型限制(必须),静态属性名称固定 static childcontexttypes = { color: proptypes.string.isrequired } // 传递给孙子组件的数据 getchildcontext() { return { color: 'red' } } render() { return ( <father></father> ) } } class child extends react.component { // 类型限制,静态属性名字固定 static contexttypes = { color: proptypes.string } render() { return ( // 从上下文对象中获取爷爷组件传递过来的数据 <h1 style={{ color: this.context.color }}>爷爷告诉文字是红色的</h1> ) } } class father extends react.component { render() { return ( <child></child> ) } }
npm i -s react-router-dom
router
组件本身只是一个容器,真正的路由要通过route组件
定义<router></router>
作为根容器,包裹整个应用(jsx)
<link to="/movie"></link>
作为链接地址,并指定to
属性<route path="/" compoent={movie}></route>
展示路由内容// 1 导入组件 import { hashrouter as router, link, route } from 'react-router-dom' // 2 使用 <router> <router> // 3 设置 link <menu.item key="1"><link to="/">首页</link></menu.item> <menu.item key="2"><link to="/movie">电影</link></menu.item> <menu.item key="3"><link to="/about">关于</link></menu.item> // 4 设置 route // exact 表示:绝对匹配(完全匹配,只匹配:/) <route exact path="/" component={homecontainer}></route> <route path="/movie" component={moviecontainer}></route> <route path="/about" component={aboutcontainer}></route> </router>
<router></router>
:作为整个组件的根元素,是路由容器,只能有一个唯一的子元素<link></link>
:类似于vue中的<router-link></router-link>
标签,to
属性指定路由地址<route></route>
:类似于vue中的<router-view></router-view>
,指定路由内容(组件)展示位置route
中的path属性来配置路由参数this.props.match.params
获取// 配置路由参数 <route path="/movie/:movietype"></route> // 获取路由参数 const type = this.props.match.params.movietype
history.push()
方法用于在js中实现页面跳转history.go(-1)
用来实现页面的前进(1)和后退(-1)this.props.history.push('/movie/moviedetail/' + movieid)
fetch()
方法返回一个promise
对象fetch 基本使用
/* 通过fetch请求回来的数据,是一个promise对象. 调用then()方法,通过参数response,获取到响应对象 调用 response.json() 方法,解析服务器响应数据 再次调用then()方法,通过参数data,就获取到数据了 */ fetch('/api/movie/' + this.state.movietype) // response.json() 读取response对象,并返回一个被解析为json格式的promise对象 .then((response) => response.json()) // 通过 data 获取到数据 .then((data) => { console.log(data); this.setstate({ movielist: data.subjects, loaing: false }) })
推荐大家使用fundebug,一款很好用的bug监控工具~
npm i -s fetch-jsonp
jsonp
实现跨域获取数据,只能获取get请求fetch-jsonp
/* movielist.js */ fetchjsonp('https://api.douban.com/v2/movie/in_theaters') .then(rep => rep.json()) .then(data => { console.log(data) })
webpack-dev-server
代理配置如下:// webpack-dev-server的配置 devserver: { // https://webpack.js.org/configuration/dev-server/#devserver-proxy // https://github.com/chimurai/http-proxy-middleware#http-proxy-options // http://www.jianshu.com/p/3bdff821f859 proxy: { // 使用:/api/movie/in_theaters // 访问 ‘/api/movie/in_theaters’ ==> 'https://api.douban.com/v2/movie/in_theaters' '/api': { // 代理的目标服务器地址 target: 'https://api.douban.com/v2', // https请求需要该设置 secure: false, // 必须设置该项 changeorigin: true, // '/api/movie/in_theaters' 路径重写为:'/movie/in_theaters' pathrewrite: {"^/api" : ""} } } } /* movielist.js */ fetch('/api/movie/in_theaters') .then(function(data) { // 将服务器返回的数据转化为 json 格式 return data.json() }) .then(function(rep) { // 获取上面格式化后的数据 console.log(rep); })
// 通过express的中间件来处理所有请求 app.use('*', function (req, res, next) { // 设置请求头为允许跨域 res.header('access-control-allow-origin', '*'); // 设置服务器支持的所有头信息字段 res.header('access-control-allow-headers', 'content-type,content-length, authorization,accept,x-requested-with'); // 设置服务器支持的所有跨域请求的方法 res.header('access-control-allow-methods', 'post,get'); // next()方法表示进入下一个路由 next(); });
getstate()
:获取statedispatch(action)
:更新state/* action */ // 在 redux 中,action 就是一个对象 // action 必须提供一个:type属性,表示当前动作的标识 // 其他的参数:表示这个动作需要用到的一些数据 { type: 'add_todo', name: '要添加的任务名称' } // 这个动作表示要切换任务状态 { type: 'toggle_todo', id: 1 } /* reducer */ // 第一个参数:表示状态(数据),我们需要给初始状态设置默认值 // 第二个参数:表示 action 行为 function todo(state = [], action) { switch(action.type) { case 'add_todo': state.push({ id: math.random(), name: action.name, completed: false }) return state case 'toggle_todo': for(var i = 0; i < state.length; i++) { if (state[i].id === action.id) { state[i].completed = !state[i].completed break } } return state default: return state } } // 要执行 add_todo 这个动作: dispatch( { type: 'add_todo', name: '要添加的任务名称' } ) // 内部会调用 reducer todo(undefined, { type: 'add_todo', name: '要添加的任务名称' })
推荐大家使用fundebug,一款很好用的bug监控工具~
如对本文有疑问, 点击进行留言回复!!
150Vue-Router路由概述+基本使用router-view占位符+重定向redirect
网友评论