1:什么是React?javascript
用来构建Ui的 javascript库 React不是一个MVC框架,仅仅是视图层的库。
2:特色?html
使用JSX语法,建立组件,实现组件化开发,为函数式的Ui编程打开大门。 性能: 经过diff算法和虚拟DOM实现视图的高效更新。 html仅仅是个开始。
3: React的核心?java
虚拟DOM【React将DOM抽象为虚拟DOM,虚拟DOM其实就是用一个对象来描述DOM,经过对比先后两个对象的差别,最终只把变化的的部分从新 渲染,提升渲染的效率】 diff算法(虚拟DOM的加速器,提高React性能的法宝)【使用React的时候,在某个时间点render()函数建立了一颗React元素树, 在下一个 state或者props更新的时候,render()函数会建立一颗新的React元素树,React将对比这两棵树的不一样之处,计算出如何高效的的更 新UI】
4:diff算法说明?node
4.1:【两棵树的根元素类型不一样,React会先销毁旧树,建立新树】
// 旧树
<div>react
<Counter/>
</div>webpack
// 新树
<span>git
<Counter />
</span>es6
执行过程 destoey Counter => insert Countergithub
4.2: [类型相同的React DOM元素,React会对比二者的属性是否相同,只更新不一样的属性] [当处理完这个DOM节点的时候,React会递归处理子节点]
// 旧
<div className="before" title="stuff" />
// 新
<div className="after" title="stuff" />
只更新:className 属性web
// 旧
<div style={{color: 'red', fontWeight: 'bold'}} />
// 新
<div style={{color: 'green', fontWeight: 'bold'}} />
只更新:color属性
4.3: 4.3.1: [当在子节点的后边添加一个节点,这时候两棵树的转化工做执行的就很好]
// 旧
<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
4.3.2:[在开始的位置添加一个元素]
// 旧
<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>
在没有key属性时执行过程:
React将改变每个子删除从新建立,而非保持 <li>Duke</li> 和 <li>Villanova</li> 不变
4.3.3:[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”仅仅移动位置便可 说明: key属性在React内部使用,但不会传递给你的组件。 在遍历属性的时候,推荐在组件中使用key属性: <li key={ item.id }>{ item.name }</li> key只须要保值和他的兄弟节点惟一便可,不须要全局惟一 尽量的减小数组index做为key,数组中插入元素等操做的时候,会使得效率低下
5:React的基本使用?
npm install -S react react-dom [react 是React库的入口点] [react-dom 提供了针对DOM的方法,好比把建立的虚拟DOM,渲染到页面上去]
// 引入
import React from 'react'
import ReactDOM from 'react-dom'
// 建立虚拟DOM
// ['元素名称', ‘元素属性对象’, ‘当前元素得子元素string || createElement()返回值’]
const divVd = React.createElement('div', {
title: 'hello world'
}, 'Hello React!!!')
// 渲染
// ['虚拟DOM对象', ‘dom对象表示渲染到哪一个元素上内’, 回调函数]
ReactDOM.render(divVd, document.getElementById('app'))
说明: createElement()方式,代码编写不友好,太过于复杂
6:JSX的基本使用?
JSX最终会被编译为createElement()方法 JSX语法炫耀经过babel-preset-react 编译后,才能被解析执行 npm install -D babel-preset-react (依赖与:babel-core/babel-loader)
/ 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'))
6.1:JSX的注意点?
[jsx元素添加类名 className 代替 class] [label的for属性 使用htmlFor进行替换] [使用{}写js代码] [只能使用表达式,不能使用语句]
7:React组件?
React组件可让你把UI分割为独立的可复用的,并将每一片断 概念上讲,组件就像js的函数,它们接受用户传入的prop,而且返回一个React对象,用来展描述展现在页面中的内容 7.1: React建立组件的两种方式? 经过JS函数建立(无状态组件) 经过 class 建立(有状态组件)
分类使用:
组件单纯为了展现数据,可使用哈数组件 组件有必定的业务逻辑,须要操做数据,可使用calss组件,阿里进行更改state里面的值 7.1.1:函数建立? [函数名必须为大写字母开头,React经过这个特色来判断师是不是一个组件] [函数必须有返回值,返回值可使JSX对象或者null] [返回的JSX,必须有一个根元素] [组件的返回值使用()进行包裹,避免换行]
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="wcj" />, document.getElementById('app'))
7.1.2: class建立 在es6中class仅仅是一个语法糖,不是真正的类,本质上仍是构造+原型 实现继承
class Person {
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 America extends Person{
constructor() { // 必须调用super(), super表示父类的构造函数 super() this.skin = 'white' this.eyeColor = 'white' }
}
// 建立React独对象
// React对象继承的字眼是React.Component
class Shooping List extends React.Component{
constructor(props) { super(props) } // class建立组件的时候,必须有render方法,且显示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> ) }
}
7.1.3: 组件单独封装
import React from 'react'
function Hello(props) {
return ( <div> <div>这是Hello2组件</div> <h1>这是大大的H1标签,我大,我骄傲!!!</h1> <h6>这是小小的h6标签,我小,我傲娇!!!</h6> </div> )
}
export default Hello
//其余地方引用
import Hello from './components/Hello'
8: props 与 state?
8.1: props [给组件传递数据,通常用在父子组件之间] [React把传递给组件的属性转化为一个对象交给props] [props是只读的,没法给props添加或者修改属性] 8.2: state [用来给组件提供组件内部使用的数据] [经过class建立的组件才具备状态] [状态是私有的,彻底由组件来控制] [不要在state里面添加render()方法中不须要的数据,会影响渲染性能] [不要在render方法中调用setState()方法来修改state的值]
class Hello extentds React.Component{
constructor(props) { super() this,state = { gender: 'male' } } render() { return ( <div>性别: { this.state.gender }</div> ) }
}
9: 组件的生命周期?
组件的生命后期包含三个部阶段 建立阶段(Mounting)、运行和交互阶段(Updating)、卸载阶段(Unmounting) 9.1: 建立阶段(Mounting) [constructor()] [componentWillMount()] [render()] [componentDidMount()] 9.2: 运行和交互阶段(Updating) [componentWillReceiveProps()] [shouldComponentUpdate()] [componentWillUpdate()] [render()] [componentDidUpdate()] 9.3: 卸载阶段(Unmounting) [componentWillUnmount()] 9.4:详述? 9.4.1: constructor()
class Greeting extends React.Component{
constructor(props) { // 获取props super(props) // 初始化 this.state = { count: props.initCount } }
}
// 初始化 props
// 经过静态属性defaultProps 来设置
Greeting.defaultProps = {
initCount : 0
}
9.4.2: componentWillMount() [组件被挂在在页面以前调用] [没法获取页面中的dom对象] [可使用setState()改变状态值]
componentWillMount() {
console.warn(document.getElementById('btn')) // null
this.setState({
count: this.state.count + 1
})
}
9.4.3: render() [渲染组件到页面中,没法获取页面中的dom对象] [不要在render方法中调用setState()方法,不然会递归渲染] [缘由说明: 状态改变会从新调用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>
)
}
9.4.4: componentDidMount() [组件已经挂在到页面中了] [能够进行dom操做] [能够经过setState()修改状态的值] [在这里会修改状态会从新渲染]
componentDidMount() {
// 此时,就能够获取到组件内部的DOM对象
console.warn('componentDidMount', document.getElementById('btn'))
}
9.4.5: compomentWillReceiveProps() [组件接收到新的props钱出发这个事件] [能够经过this.props接收之前传递的值,进行比较] [若你须要响应属性的改变,能够经过对比this.props和nextProps并在该方法中使用this.setState()处理状态改变] [修改state不会触发该方法]
componentWillReceiveProps(nextProps) {
console.warn('componentWillReceiveProps', nextProps)
}
9.4.6: shouldComponentUpdate() [根据这个返回值肯定是否进行渲染组件,返回true则进行从新渲染,不然不渲染] [经过某个条件进行渲染组件,下降组件渲染频率,提高组件性能] [这个方法必须返回布尔值] [若是返回值是false,那么后续的render()将不会执行]
// - 参数:
// - 第一个参数:最新属性对象
// - 第二个参数:最新状态对象
shouldComponentUpdate(nextProps, nextState) {
console.warn('shouldComponentUpdate', nextProps, nextState)
return nextState.count % 2 === 0
}
9.4.7: componentWillUpdate() [组件将要更新] [最新的属性和状态对象] [不能修改状态,不然会重复渲染]
componentWillUpdate(nextProps, nextState) {
console.warn('componentWillUpdate', nextProps, nextState)
}
9.4.8: render() [从新渲染组件] [这个函数可以屡次执行,只要组件的属性或者状态改变了,这个方法就会从新执行] 9.4.8:componentDidUpdate() [组件已经被更新] [旧的属性和状态对象]
componentDidUpdate(prevProps, prevState) {
console.warn('componentDidUpdate', prevProps, prevState)
}
9.4.9: componentWillUnmount() [清除定时器] [组件一生只能执行依次]
10: state 和 setState
[使用setState()方法修改,状态改变后,React会从新渲染组件] [不要直接修改state的值,这样不会从新渲染组件]
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
}))
}
11:组件绑定事件
[ref获取dom对象] [onClick驼峰命名事件绑定]
<input type="button" value="触发单击事件"
onClick={this.handleCountAdd}
onMouseEnter={this.handleMouseEnter}
/>
11.1:事件绑定? [经过bind绑定] [经过箭头函数绑定] 【bind可以调用函数,改变函数内部的this指向,并返回一个新的函数】 【bind第一个参数表示返回函数中的this的指向,后面的参数表示传递给函数的参数】
// 1:自定义方法:
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>
)
}
//2:构造函数中绑定
constructor() {
super()
this.handleBtnClick = this.handleBtnClick.bind(this)
}
// render() 方法中:
<button onClick={ this.handleBtnClick }>事件中this的处理</button>
11.2: props校验? npm install -s prop-types
// 引入模块
import PropTypes from 'prop-types'
// 使用
static propTypes = { initCount: PropTypes.number, // 规定属性的类型 initAge: PropTypes.number.required // 规定属性的类型,且规定为必传字段
}
12: React 单项数据流?
[数据流方向: 自上而下,也就是只能从父组件传递到子组件] [数据都是从父组件提供的,子组件想要使用数据,必须从父组件中去获取] [若是多个组件都要使用某个数据,那么最好将这这部数据共享是状态提高父集当中进行管理] 12.1: 组件通信
父 ---》 子 props
子 ---》 父组件经过prop传递回调函数给子组件,子组件调用函数将数据参数传递给父组件。
兄弟组件 React是单项数据流,所以须要借助于父组件进行传递,经过父组件的回调进行修改兄弟组件的props.
class Component {
constructor(props){
super(props);
}
render(){
return ( <div title={this.props.title}></div> )
}
}
<Component title="test"/>//调用title就传进去了
父子传值
class Child extends React.Component{
constructor(props){
super(props); this.state = {}
}
render(){
return ( <div> {this.props.text} <br /> <button onClick={this.props.refreshParent}> 更新父组件 </button> </div> )
}
}
class Parent extends React.Component{
constructor(props){
super(props); this.state = {}
}
refreshChild(){
return (e)=>{ this.setState({ childText: "父组件沟通子组件成功", }) }
}
refreshParent(){
this.setState({ parentText: "子组件沟通父组件成功", })
}
render(){
return ( <div> <h1>父子组件沟通</h1> <button onClick={this.refreshChild()} > 更新子组件 </button> <Child text={this.state.childText || "子组件未更新"} refreshParent={this.refreshParent.bind(this)} /> {this.state.parentText || "父组件未更新"} </div> )
}
}
兄弟传值(context上下文的方式进行传值)
class Brother1 extends React.Component{
constructor(props){
super(props); this.state = {}
}
render(){
return ( <div> <button onClick={this.context.refresh}> 更新兄弟组件 </button> </div> )
}
}
Brother1.contextTypes = {
refresh: React.PropTypes.any
}
class Brother2 extends React.Component{
constructor(props){
super(props); this.state = {}
}
render(){
return ( <div> {this.context.text || "兄弟组件未更新"} </div> )
}
}
Brother2.contextTypes = {
text: React.PropTypes.any
}
class Parent extends React.Component{
constructor(props){
super(props); this.state = {}
}
getChildContext(){
return { refresh: this.refresh(), text: this.state.text, } }
refresh(){
return (e)=>{ this.setState({ text: "兄弟组件沟通成功", }) }
}
render(){
return ( <div> <h2>兄弟组件沟通</h2> <Brother1 /> <Brother2 text={this.state.text}/> </div> )
}
}
Parent.childContextTypes = {
refresh: React.PropTypes.any,
text: React.PropTypes.any,
}
跨级传值
Context 做用属性:跨级传递数据,避免向下每层手动的传递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> )
}
}
13: 路由管理React-router
npm install react-router-dom -Save 13.1: 使用? [引入路由组件] [使用 <Router></Router> 做为根容器,包裹整个应用(JSX)] [使用 <Link to="/movie"></Link> 做为连接地址,并指定to属性] [使用 <Route path="/" compoent={Movie}></Route> 展现路由内容] 【<Router></Router>做为整个组件的根组件,是路由容器,只能是惟一的子元素】 【<Link></Link> 相似与Vue中的<router-link></router-link>, to属性指定路由地址】 【<Route></Route>相似于Vue中的<router-view></router-view>,指定路由内容(组件)展现的位置】
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> 13.2: 路由传参?
// 配置路由参数
<Route path="/movie/:movieType"></Route>
// 获取路由参数
const type = this.props.match.params.movieType
13.3: 路由跳转?
this.props.history.push('/movie/movieDetail/' + movieId)
history.go(-1) 用来实现页面的前进(1)和后退(-1)
history.push() 方法用于在JS中实现页面跳转
14: fetch?
[fetch 是一个现代的概念, 等同于XMLHttpRequest, 它提供了许多与XMLHttpRequest相同的功能,但被设计成更具备可扩展性和高效性]
/*
经过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 })
})
/*
*/
fetch(url, {
method: 'POST', header: { "Content-Type": "application/x-www-form-urlencoded" } body: "key1=value1&key2=value2"
}).then(res => {
console.log(res)
}, err => {
console.log(err)
}).catch(e => {
console.log(e)
})
15: 跨域获取数据的三种方式?
JSONP
代理
CORS
npm install -s fetch-jsonp [利用JSONP实现跨域获取数据的时候,只能获取get请求] 【限制: 1 只能发送GET请求 2 须要服务器支持JSONP请求】
JSONP
fetchJsonp('https://api.douban.com/v2/mov...')
.then(rep => rep.json())
.then(data => { console.log(data) })
代理
【webpack-dev-server 代理配置以下】 【问题:webpack-dev-server 是开发期间使用的工具,项目上线了就再也不使用 webpack-dev-server】 【解决:项目上线后的代码,也是会部署到一个服务器中,这个服务器配置了代理功能便可(要求两个服务器中配置的代理规则相同】
// webpack-dev-server的配置
devServer: {
// https://webpack.js.org/config...
// https://github.com/chimurai/h...
// http://www.jianshu.com/p/3bdf...
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);
})
CORS-服务器端跨域
// 经过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();
});
16: redux 状态管理工具,用来管理应用中的数据
16.1: 核心? Store: [Redux应该只有一个store] [getState() 获取state] [dispatch(action) 用来修改state]
/ action/
【 在redux中, action就是一个对象。】
【action必须提供一个: type属性,表示当前动做的标识】
【其余参数,标识这个动做须要用到的数据】
{ type: ‘ADD_TOTD’,name: '要添加的任务名称'}
{type: 'TOGGLE_TOTD', 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: '要添加的任务名称' } )
// 内部会调用 reducertodo(undefined, { type: 'ADD_TODO', name: '要添加的任务名称' })