zoukankan      html  css  js  c++  java
  • react学习笔记一些整理

    一、事件绑定 this 指向

    1. 更改 this 指向的三个方式
    • 箭头函数
    • Function.prototype.bind()
    • class 的实例方法
    001 - 箭头函数的方式
    1. 利用了箭头函数自身不绑定 this 的特点
    2. render() 方法中的 this 为组件实例,可以获取到 setState()
    export default class App extends React.Component {
      state = {
        age: 3
      }
    
      addHandle() {
        this.setState({
          age: this.state.age + 1
        })
      }
    
      render() {
        return (
          <div>
            {/* 箭头函数的方式改变 this 执行 */}
            <button onClick={() => this.addHandle()}>更改数据</button>
            <p>{this.state.age}</p>
          </div>
        )
      }
    }
    

      

    002 - Function.prototype.bind()
    1. 利用 ES5 中的 bind方法,将事件处理程序中的 this 与组件实例绑定到一起
    2. 这个方案是官方推荐的方案
    export default class App extends React.Component {
      constructor () {
        super()
        this.state = {
          age: 3
        }
        // 利用ES5中的bind方法,将事件处理程序中的this与组件实例绑定到一起
        this.addHandle = this.addHandle.bind(this)
      }
    
      addHandle() {
        this.setState({
          age: this.state.age + 1
        })
      }
    
      render() {
        return (
          <div>
            {/* 箭头函数的方式改变 this 执行 */}
            <button onClick={this.addHandle}>更改数据</button>
            <p>{this.state.age}</p>
          </div>
        )
      }
    }
    003 - class 实例方法
    1. 利用箭头函数形式的 class 实例方法
    2. 注意:该语法是实验性语法,但是,由于 babel 的存在可以直接使用
    export default class App extends React.Component {
      constructor () {
        super()
        this.state = {
          age: 3
        }
      }
    
      // 利用箭头函数形式的class实例方法
      addHandle = () => {
        this.setState({
          age: this.state.age + 1
        })
      }
    
      render() {
        return (
          <div>
            <button onClick={this.addHandle}>更改数据</button>
            <p>{this.state.age}</p>
          </div>
        )
      }
    }
    004 - 绑定 this 总结
    1. 推荐:使用 class 的实例方法
    2. 箭头函数
    3. bind -- 是官网推荐的

    二、axios、fetch

    • 1.React本身只关注于界面, 并不包含发送ajax请求的代码
    • 2.前端应用需要通过ajax请求与后台进行交互(json数据)
    • 3.react应用中需要集成第三方ajax库(或自己封装)

    2.1.2. 常用的ajax请求库

    • 1.jQuery: 比较重, 如果需要另外引入不建议使用
    • 2.axios: 轻量级, 建议使用
      • 1)封装XmlHttpRequest对象的ajax
      •     promise风格
      • 3)可以用在浏览器端和node服务器端

    1)GET请求

    axios.get('/user?ID=12345')
      .then(function (response) {
        console.log(response.data);
      })
      .catch(function (error) {
        console.log(error);
      });
    
    axios.get('/user', {
        params: {
          ID: 12345
        }
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

    2)POST请求

    axios.post('/user', {
      firstName: 'Fred',
      lastName: 'Flintstone'
    })
    .then(function (response) {
    console.log(response);
    })
    .catch(function (error) {
    console.log(error);
    });
    

     2.1.3相关API

    1)GET请求

    fetch(url).then(function(response) {
        return response.json()
      }).then(function(data) {
        console.log(data)
      }).catch(function(e) {
        console.log(e)
      });
    

      

    2)POST请求

      fetch(url, {
        method: "POST",
        body: JSON.stringify(data),
      }).then(function(data) {
        console.log(data)
      }).catch(function(e) {
        console.log(e)
      })
    

    3)实例

    //发送网络请求---使用fetch发送(优化)
    		try {
    			const response= await fetch(`/api1/search/users2?q=${keyWord}`)
    			const data = await response.json()
    			console.log(data);
    			PubSub.publish('atguigu',{isLoading:false,users:data.items})
    		} catch (error) {
    			console.log('请求出错',error);
    			PubSub.publish('atguigu',{isLoading:false,err:error.message})
    		}
    	}

    三、组件三大核心属性1: state

    • 效果

    需求: 定义一个展示天气信息的组件

    1.默认展示天气炎热 或 凉爽

    2.点击文字切换天气

    • 理解

      • 1.state是组件对象最重要的属性, 值是对象(可以包含多个key-value的组合)
      • 2.组件被称为"状态机", 通过更新组件的state来更新对应的页面显示(重新渲染组件)
    • 强烈注意

      • 1.组件中render方法中的this为组件实例对象
      • 2.组件自定义的方法中this为undefined,如何解决?
        • a)强制绑定this: 通过函数对象的bind()
        • b)箭头函数
      • 3.状态数据,不能直接修改或更新

    组件三大核心属性2: props

    • 2.3.1. 效果

    • 需求: 自定义用来显示一个人员信息的组件

      • 1.姓名必须指定,且为字符串类型;
      • 2.性别为字符串类型,如果性别没有指定,默认为男
      • 3.年龄为字符串类型,且为数字类型,默认值为18

      输入图片说明

    •  理解

      • 1.每个组件对象都会有props(properties的简写)属性
      • 2.组件标签的所有属性都保存在props中
    • 作用

      • 1.通过标签属性从组件外向组件内传递变化的数据
      • 2.注意: 组件内部不要修改props数据
    • 编码操作

    • 1.内部读取某个属性值this.props.name
    • 2.第二种方式(新):使用prop-types库进限制(需要引入prop-types库)
    • Person.propTypes = {
      name: PropTypes.string.isRequired,
      age: PropTypes.number. 
      }  
    • 3.扩展属性: 将对象的所有属性通过props传递
    • <Person {...person}/>
    • 4.默认属性值:
    • Person.defaultProps = {
          age: 18,
          sex:'男'
      }
    • 5.组件类的构造函数
    • constructor(props){
          super(props)
          console.log(props)//打印所有属性
      }

     组件三大核心属性3: refs与事件处理

    • 2.4.1. 效果

    • 需求: 自定义组件, 功能说明如下:
    • 点击按钮, 提示第一个输入框中的值
    • 当第2个输入框失去焦点时, 提示这个输入框中的值

    输入图片说明

    • 理解

    组件内的标签可以定义ref属性来标识自己

    • 编码

    1.字符串形式的ref
    <input ref="input1"/>

    2.回调形式的ref
    <input ref={(c)=>{this.input1 = c}}/>
    3.createRef创建ref容器

    myRef = React.createRef()
    <input ref={this.myRef}/>
    

    事件处理

    • 1.通过onXxx属性指定事件处理函数(注意大小写)
      • 1)React使用的是自定义(合成)事件, 而不是使用的原生DOM事件
      • 2)React中的事件是通过事件委托方式处理的(委托给组件最外层的元素)
    • 2.通过event.target得到发生事件的DOM元素对象

    四、组件的生命周期

    •  理解

      • 1.组件从创建到死亡它会经历一些特定的阶段。
      • 2.React组件中包含一系列勾子函数(生命周期回调函数), 会在特定的时刻调用。
      • 3.我们在定义组件时,会在特定的生命周期回调函数中,做特定的工作。
    • 生命周期流程图

    • 生命周期的三个阶段(新)

      • 初始化阶段: 由ReactDOM.render()触发---初次渲染
        • 1.constructor()
        • 2.getDerivedStateFromProps
        • 3.render()
        • 4.componentDidMount()
      • 更新阶段: 由组件内部this.setSate()或父组件重新render触发
        • 1.getDerivedStateFromProps
        • 2.shouldComponentUpdate()
        • 3.render()
        • 4.getSnapshotBeforeUpdate
        • 5.componentDidUpdate()
      • 卸载组件: 由ReactDOM.unmountComponentAtNode()触发
        • 1.componentWillUnmount()
    • 重要的勾子

      • 1.render:初始化渲染或更新渲染调用
      • 2.componentDidMount:开启监听, 发送ajax请求
      • 3.componentWillUnmount:做一些收尾工作, 如: 清理定时器
    • 即将废弃的勾子

      • 1.componentWillMount
      • 2.componentWillReceiveProps
      • 3.componentWillUpdate

    redux?  

    好笔记:react学习笔记_冷月心的博客-CSDN博客_react学习

      

      

  • 相关阅读:
    SpringBoot整合Ehcache
    SpringCache整合Redis
    SpringBoot使用mongo搭建RESTful风格
    SpringBoot使用JPA搭建RESTful风格
    SpringBoot操作mongo的两种方法
    Nginx负载均衡
    【Java杂货铺】用Security做权限极简入门
    【Java杂货铺】JVM#虚拟机加载机制
    【Java杂货铺】JVM#Class类结构
    【Java杂货铺】JVM#Java高墙之GC与内存分配策略
  • 原文地址:https://www.cnblogs.com/wmlcn/p/15084902.html
Copyright © 2011-2022 走看看