React零碎记忆

1:什么是React?

用来构建Ui的 javascript库
React不是一个MVC框架,仅仅是视图层的库。

2:特点?

使用JSX语法,创建组件,实现组件化开发,为函数式的Ui编程打开大门。
性能: 通过diff算法和虚拟DOM实现视图的高效更新。
html仅仅是个开始。

3: React的核心?

虚拟DOM【React将DOM抽象为虚拟DOM,虚拟DOM其实就是用一个对象来描述DOM,通过对比前后两个对象的差异,最终只把变化的的部分重新                     渲染,提高渲染的效率】
diff算法(虚拟DOM的加速器,提升React性能的法宝)【使用React的时候,在某个时间点render()函数创建了一颗React元素树, 在下一个                           state或者props更新的时候,render()函数会创建一颗新的React元素树,React将对比这两棵树的不同之处,计算出如何高效的的更                        新UI】

4:diff算法说明?

4.1:【两棵树的根元素类型不同,React会先销毁旧树,创建新树】

// 旧树

// 新树

执行过程 destoey Counter => insert Counter

 4.2: [类型相同的React DOM元素,React会对比两者的属性是否相同,只更新不同的属性]
        [当处理完这个DOM节点的时候,React会递归处理子节点]

// 旧


// 新

只更新:className 属性

// 旧


// 新

只更新:color属性

  4.3:
       4.3.1: [当在子节点的后边添加一个节点,这时候两棵树的转化工作执行的就很好]

// 旧


  • first

  • second

// 新


  • first

  • second

  • third

执行过程:
React会匹配新旧两个

  • first
  • ,匹配两个
  • second
  • ,然后添加
  • third
  • tree

           4.3.2:[在开始的位置添加一个元素]

    // 旧


    • Duke

    • Villanova

    // 新


    • Connecticut

    • Duke

    • Villanova

    在没有key属性时执行过程:
    React将改变每一个子删除重新创建,而非保持

  • Duke
  • Villanova
  • 不变

           4.3.3:[key属性]

    // 旧


    • Duke

    • Villanova

    // 新


    • Connecticut

    • Duke

    • Villanova

    执行过程:

    现在React知道带有key “2014”的元素是新的,对于“2015”、“2016”仅仅移动位置即可
      说明: key属性在React内部使用,但不会传递给你的组件。
                 在遍历属性的时候,推荐在组件中使用key属性: 
  • { item.name }
  • 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 = (

    Hello JSX!

    )

    / 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 (
    

    Shopping List for {props.name}

    • Instagram
    • WhatsApp
    )

    }

    ReactDOM.render(, 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 (    
             

    Shopping List for {this.props.name}

    • Instagram
    • WhatsApp
    ) }

    }

          7.1.3: 组件单独封装

    import React from 'react'
    function Hello(props) {

    return (
    
    这是Hello2组件

    这是大大的H1标签,我大,我骄傲!!!

    这是小小的h6标签,我小,我傲娇!!!
    )

    }

    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 (
              
    性别: { this.state.gender }
    ) }

    }
    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 (

    { this.state.count === 4 ? null : }

    )
    }

           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驼峰命名事件绑定]

    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 (

    {this.state.msg}

    )
    }

    //2:构造函数中绑定
    constructor() {
    super()

    this.handleBtnClick = this.handleBtnClick.bind(this)
    }

    // render() 方法中:

     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 (
        
    )

    }
    }
    //调用title就传进去了
    父子传值
    class Child extends React.Component{
    constructor(props){

    super(props);
    this.state = {}

    }

    render(){

    return (
      
    {this.props.text}
    )

    }
    }
    class Parent extends React.Component{
    constructor(props){

    super(props);
    this.state = {}

    }
    refreshChild(){

    return (e)=>{
      this.setState({
        childText: "父组件沟通子组件成功",
      })
    }

    }
    refreshParent(){

    this.setState({
      parentText: "子组件沟通父组件成功",
    })

    }
    render(){

    return (
      

    父子组件沟通

    {this.state.parentText || "父组件未更新"}
    )

    }
    }

    兄弟传值(context上下文的方式进行传值)
    class Brother1 extends React.Component{
    constructor(props){

    super(props);
    this.state = {}

    }
    render(){

    return (
      
    )

    }
    }
    Brother1.contextTypes = {
    refresh: React.PropTypes.any
    }

    class Brother2 extends React.Component{
    constructor(props){

    super(props);
    this.state = {}

    }
    render(){

    return (
      
    {this.context.text || "兄弟组件未更新"}
    )

    }
    }
    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 (
      

    兄弟组件沟通

    )

    }
    }
    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 (
      
    )

    }
    }

    class Child extends React.Component {
    // 类型限制,静态属性名字固定
    static contextTypes = {

    color: PropTypes.string

    }

    render() {

    return (
      // 从上下文对象中获取爷爷组件传递过来的数据
      

    爷爷告诉文字是红色的

    )

    }
    }

    class Father extends React.Component {
    render() {

    return (
      
    )

    }
    }
    13: 路由管理React-router

     npm install react-router-dom -Save
     13.1: 使用?
          [引入路由组件]
          [使用  作为根容器,包裹整个应用(JSX)]
          [使用  作为链接地址,并指定to属性]
          [使用  展示路由内容]
          【作为整个组件的根组件,是路由容器,只能是唯一的子元素】
          【 类似与Vue中的, to属性指定路由地址】
          【类似于Vue中的,指定路由内容(组件)展示的位置】

    1: 引入组件

    import { HashRouter as Router, Link, Route } from "react-router-dom"

    2: 使用

    
    // 3 设置 Link
    首页
    电影
    关于
    
    // 4 设置 Route
    // exact 表示:绝对匹配(完全匹配,只匹配:/)
    
    
    
     
    13.2: 路由传参?

    // 配置路由参数

    // 获取路由参数
    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: '要添加的任务名称' } )

    // 内部会调用 reducer
    todo(undefined, { type: 'ADD_TODO', name: '要添加的任务名称' })

    你可能感兴趣的:(web)