【前端学习】React学习笔记-react扩展:hook、组件通信、setState、lazyLoad、Context、Fragment、组件优化、render props、错误边界

8 篇文章 0 订阅

跟着尚硅谷的天禹老师学习React
看视频可以直接点击 b站视频地址
下面的内容相当一部分是来自于课件内容。

1. setState

setState更新状态的2种写法

	(1). setState(stateChange, [callback])------对象式的setState
            1.stateChange为状态改变对象(该对象可以体现出状态的更改)
            2.callback是可选的回调函数, 它在状态更新完毕、界面也更新后(render调用后)才被调用
					
	(2). setState(updater, [callback])------函数式的setState
            1.updater为返回stateChange对象的函数。
            2.updater可以接收到state和props。
            4.callback是可选的回调函数, 它在状态更新、界面也更新后(render调用后)才被调用。
总结:
		1.对象式的setState是函数式的setState的简写方式(语法糖)
		2.使用原则:
				(1).如果新状态不依赖于原状态 ===> 使用对象方式
				(2).如果新状态依赖于原状态 ===> 使用函数方式
				(3).如果需要在setState()执行后获取最新的状态数据, 
					要在第二个callback函数中读取
  1. setState是同步方法,但是React会异步地更新视图。
import React, { Component } from "react";

export default class Demo extends Component {
  state = { count: 0 };
  add = () => {
    // 获取原来count值
    const { count } = this.state;
    // 更新状态
    this.setState({ count: count + 1 }, function () {
      console.log("视图更新完毕的回调");
    });
    console.log("调用setState后", this.state.count);
  };
  render() {
    console.log("render开始");
    return (
      <div>
        <h1>当前求和为:{this.state.count}</h1>
        <button onClick={this.add}>点我+1</button>
        {console.log("render完毕")}
      </div>
    );
  }
}

在这里插入图片描述

  1. 函数式setState的,传入的函数会接收两个值,一个是自身的state,一个是外部传入的props。
this.setState((state, props) => {
      console.log(state, props); // {count: 1}  {}
      return { count: state.count + 1 };
});

2. lazyLoad

如果项目组件很多到影响首屏性能的话,就要使用懒加载。尤其是路由组件需要懒加载。

路由组件的lazyLoad

	//1.通过React的lazy函数配合import()函数动态加载路由组件 ===> 路由组件代码会被分开打包
	const Login = lazy(()=>import('@/pages/Login'))
	
	//2.通过<Suspense>指定在加载得到路由打包文件前显示一个自定义loading界面
	<Suspense fallback={<h1>loading.....</h1>}>
        <Switch>
            <Route path="/xxx" component={Xxxx}/>
            <Redirect to="/login"/>
        </Switch>
    </Suspense>
  1. fallback指定当懒加载的组件还没有返回时的替代组件
  2. fallback指定的组件,不可以再使用懒加载引入

可以使用浏览器开发者工具来测试低网速的条件下网页的呈现。
在这里插入图片描述


3. Hooks

函数式组件没有this,所以不能访问实例对象,Hooks解决了这个问题。

1. React Hook/Hooks是什么?
(1). Hook是React 16.8.0版本增加的新特性/新语法
(2). 可以让你在函数组件中使用 state 以及其他的 React 特性
2. 三个常用的Hook

对应了实例的三个重要属性

(1). State Hook: React.useState()
(2). Effect Hook: React.useEffect()
(3). Ref Hook: React.useRef()
3. State Hook
(1). State Hook让函数组件也可以有state状态, 并进行状态数据的读写操作
(2). 语法: const [xxx, setXxx] = React.useState(initValue)  
(3). useState()说明:
        参数: 第一次初始化指定的值在内部作缓存
        返回值: 包含2个元素的数组, 第1个为内部当前状态值, 第2个为更新状态值的函数
(4). setXxx()2种写法:
        setXxx(newValue): 参数为非函数值, 直接指定新的状态值, 内部用其覆盖原来的状态值
        setXxx(value => newValue): 参数为函数, 接收原本的状态值, 返回新的状态值, 内部用其覆盖原来的状态值

Demo组件就相当于原来的render,调用次数也就是初始化一次加上后期改变状态的n次。

function Demo() {
  const [count, setCount] = React.useState(0);
  const [name, setName] = React.useState("tom");
  const add = () => {
    setCount((count) => count + 1);
  };
  const modifyName = () => {
    setName(() => "zzy");
  };
  return (
    <div>
      <h1>当前求和为:{count}</h1>
      <h1>我是:{name}</h1>
      <button onClick={add}>点我+1</button>
      <button onClick={modifyName}>点我改名</button>
    </div>
  );
}

4. Effect Hook
(1). Effect Hook 可以让你在函数组件中执行副作用操作(用于模拟类组件中的生命周期钩子)
(2). React中的副作用操作:
        发ajax请求数据获取
        设置订阅 / 启动定时器
        手动更改真实DOM
(3). 语法和说明: 
        useEffect(() => { 
          // 在此可以执行任何带副作用操作
          return () => { // 在组件卸载前执行
            // 在此做一些收尾工作, 比如清除定时器/取消订阅等
          }
        }, [stateValue]) // 如果指定的是[], 回调函数只会在第一次render()后执行
    
(4). 可以把 useEffect Hook 看做如下三个函数的组合
        componentDidMount()
        componentDidUpdate()
    	componentWillUnmount() 
  1. useEffect的第二个参数(那个数组),可以添加对某个状态的检测。只有写了空数组才是不监测任何状态;如果不传这个参数,会监测任何状态的更新。
  2. useEffect可以使用多次
5. Ref Hook
(1). Ref Hook可以在函数组件中存储/查找组件内的标签或任意其它数据
(2). 语法: const refContainer = useRef()
(3). 作用:保存标签对象,功能与React.createRef()一样
6.代码
import React, { Component } from "react";
import ReactDOM from "react-dom";

function Demo() {
  const [count, setCount] = React.useState(0);
  const add = () => {
    setCount((count) => count + 1);
  };
  const unmount = () => {
    ReactDOM.unmountComponentAtNode(document.getElementById("root"));
  };
  const showInputContent = () => {
    const { value } = input.current;
    alert(value);
  };
  const input = React.useRef();
  React.useEffect(() => {
    const timerid = setInterval(() => {
      setCount((count) => count + 1);
    }, 1000);
    return () => {
      clearInterval(timerid);
    };
  }, []);
  return (
    <div>
      <h1>当前求和为:{count}</h1>
      <input type="text" ref={input} placeholder="输入内容"></input>
      <button onClick={add}>点我+1</button>
      <button onClick={unmount}>点我卸载</button>
      <button onClick={showInputContent}>点我展示输入框内容</button>
    </div>
  );
}
export default Demo;


4. Fragment

使用

<Fragment><Fragment>
<></>

区别:空标签不允许传入props,Fragment仅可以传入key(用于遍历)

作用

可以不用必须有一个真实的DOM根标签了

在这里插入图片描述

App.js

/* App.js */
import React, { Component ,Fragment} from "react";
import Demo from "./components/fragment";
import { BrowserRouter } from "react-router-dom";
export default class App extends Component {
  render() {
    return (
      <Fragment>
        <BrowserRouter>
          <Demo />
        </BrowserRouter>
      </Fragment>
    );
  }
}

Demo.jsx

/* Demo.jsx */
import React, { Component,Fragment } from 'react'
export default class index extends Component {
  render() {
    return (
      <>
          <input></input>
          <input></input>
      </>
    )
  }
}


5. Context

理解

一种组件间通信方式, 常用于【祖组件】与【后代组件】间通信

使用

1) 创建Context容器对象:
	const XxxContext = React.createContext()  
	
2) 渲染子组时,外面包裹xxxContext.Provider, 通过value属性给后代组件传递数据:
	<xxxContext.Provider value={数据}>
		子组件
    </xxxContext.Provider>
    
3) 后代组件读取数据:

	//第一种方式:仅适用于类组件 
	  static contextType = xxxContext  // 声明接收context
	  this.context // 读取context中的value数据
	  
	//第二种方式: 函数组件与类组件都可以
	  <xxxContext.Consumer>
	    {
	      value => ( // value就是context中的value数据
	        要显示的内容
	      )
	    }
	  </xxxContext.Consumer>

注意

在应用开发中一般不用context, 一般都用它的封装react插件

一个错误在这里插入图片描述

在跟着案例走的时候,页面加载不出来,通过任务管理器发现内存增长非常快,原因是出现了循环引用,react脚手架也没有报错…找了好一会。

代码

在这里插入图片描述

import React, { Component } from "react";
import "./index.css";
const MyContext = React.createContext();
const { Provider, Consumer } = MyContext;
export default class A extends Component {
  state = { username: "tom" };
  render() {
    const { username } = this.state;
    return (
      <div className="parent">
        <h1>我是A</h1>
        <h4>我的用户名是:{username}</h4>
        {/** 这里可以使用解构赋值 {Provider} = MyContext */}
        <Provider value={{ username, age: 18 }}>
          <B />
        </Provider>
      </div>
    );
  }
}

class B extends Component {
  static contextType = MyContext;
  render() {
    const { username, age } = this.context;
    return (
      <div className="child">
        <h1>我是B</h1>
        <h4>我从A接到的用户名是:{username}</h4>
        <C />
      </div>
    );
  }
}

class C extends Component {
  static contextType = MyContext;

  render() {
    const { username, age } = this.context;
    return (
      <div className="grand">
        <h1>我是C</h1>
        <h4>我从A接到的用户名是:{username}</h4>
        <D />
      </div>
    );
  }
}
/* 函数使用Consumer来获取context中的值 */
function D() {
  return (
    <div className="grand-grand">
      <h1>我是C</h1>
      <Consumer>
        {(value) => {
          return <h4>{`姓名是${value.username},年龄是${value.age}`}</h4>;
        }}
      </Consumer>
    </div>
  );
}

6. 组件优化

Component的2个问题

  1. 只要执行setState(),即使不改变状态数据, 组件也会重新render() ==> 效率低

  2. 只当前组件重新render(), 就会自动重新render子组件,纵使子组件没有用到父组件的任何数据 ==> 效率低

效率高的做法

只有当组件的state或props数据发生改变时才重新render()

原因

Component中的shouldComponentUpdate()总是返回true

解决

办法1: 
	重写shouldComponentUpdate()方法
	比较新旧state或props数据, 如果有变化才返回true, 如果没有返回false
办法2:  
	使用PureComponent
	PureComponent重写了shouldComponentUpdate(), 只有state或props数据有变化才返回true
	注意: 
		只是进行state和props数据的浅比较, 如果只是数据对象内部数据变了, 返回false  
		不要直接修改state数据, 而是要产生新数据
项目中一般使用PureComponent来优化

代码

import React, { PureComponent } from "react";
import "./index.css";

export default class Parent extends PureComponent {
  state = { carName: "奔驰c36", stus: ["小张", "小李", "小王"] };

  addStu = () => {
	// 要写纯函数
    /* const {stus} = this.state
		stus.unshift('小刘')
		this.setState({stus}) */

    const { stus } = this.state;
    this.setState({ stus: ["小刘", ...stus] });
  };

  changeCar = () => {
    //this.setState({carName:'迈巴赫'})

    const obj = this.state;
    obj.carName = "迈巴赫";
    console.log(obj === this.state);
    this.setState(obj);
  };
  // pureComponent内部不允许使用shouldComponentUpdate钩子
  /* shouldComponentUpdate(nextProps,nextState){
		// console.log(this.props,this.state); //目前的props和state
		// console.log(nextProps,nextState); //接下要变化的目标props,目标state
		return !this.state.carName === nextState.carName
	} */

  render() {
    console.log("Parent---render");
    const { carName } = this.state;
    return (
      <div className="parent">
        <h3>我是Parent组件</h3>
        {this.state.stus}&nbsp;
        <span>我的车名字是:{carName}</span>
        <br />
        <button onClick={this.changeCar}>点我换车</button>
        <button onClick={this.addStu}>添加一个小刘</button>
        <Child carName="奥拓" />
      </div>
    );
  }
}

class Child extends PureComponent {
  // pureComponent内部不允许使用shouldComponentUpdate钩子
  /* shouldComponentUpdate(nextProps,nextState){
		console.log(this.props,this.state); //目前的props和state
		console.log(nextProps,nextState); //接下要变化的目标props,目标state
		return !this.props.carName === nextProps.carName
	} */

  render() {
    console.log("Child---render");
    return (
      <div className="child">
        <h3>我是Child组件</h3>
        <span>我接到的车是:{this.props.carName}</span>
      </div>
    );
  }
}


7. render props

如何向组件内部动态传入带内容的结构(标签)?

Vue中: 
	使用slot技术, 也就是通过组件标签体传入结构  <A><B/></A>
React中:
	使用children props: 通过组件标签体传入结构
	使用render props: 通过组件标签属性传入结构,而且可以携带数据,一般用render函数属性

children props

<A>
  <B>xxxx</B>
</A>
{this.props.children}
问题: 如果B组件需要A组件内的数据, ==> 做不到 

render props

<A render={(data) => <C data={data}></C>}></A>
A组件: {this.props.render(内部state数据)}
C组件: 读取A组件传入的数据显示 {this.props.data} 
import React, { Component } from 'react'
import './index.css'

export default class Parent extends Component {
	render() {
		return (
			<div className="parent">
				<h3>我是Parent组件</h3>
				<A render={(name)=><B name={name}/>}/>
			</div>
		)
	}
}

class A extends Component {
	state = {name:'tom'}
	render() {
		console.log(this.props);
		const {name} = this.state
		return (
			<div className="a">
				<h3>我是A组件</h3>
				{this.props.render(name)}
			</div>
		)
	}
}

class B extends Component {
	render() {
		console.log('B--render');
		return (
			<div className="b">
				<h3>我是B组件,{this.props.name}</h3>
			</div>
		)
	}
}


8. 错误边界

理解:

错误边界(Error boundary):用来捕获后代组件错误,渲染出备用页面

特点:

只能捕获后代组件生命周期产生的错误,不能捕获自己组件产生的错误和其他组件在合成事件、定时器中产生的错误。

使用方式:

getDerivedStateFromError配合componentDidCatch,只有生产环境才能使用错误边界。

// 生命周期函数,一旦后台组件报错,就会触发
static getDerivedStateFromError(error) {
    console.log(error);
    // 在render之前触发
    // 返回新的state
    return {
        hasError: true,
    };
}

componentDidCatch(error, info) {
    // 统计页面的错误。发送请求发送到后台去
    console.log(error, info);
}
代码

Parent.jsx

/* Parent.jsx */
import React, { Component } from 'react'
import Child from './Child'

export default class Parent extends Component {

	state = {
		hasError:'' //用于标识子组件是否产生错误
	}

	//当Parent的子组件出现报错时候,会触发getDerivedStateFromError调用,并携带错误信息
	static getDerivedStateFromError(error){
		console.log('@@@',error);
		return {hasError:error}
	}

	componentDidCatch(){
		console.log('此处统计错误,反馈给服务器,用于通知编码人员进行bug的解决');
	}

	render() {
		return (
			<div>
				<h2>我是Parent组件</h2>
				{this.state.hasError ? <h2>当前网络不稳定,稍后再试</h2> : <Child/>}
			</div>
		)
	}
}

Child.jsx

import React, { Component } from 'react'

export default class Child extends Component {
	state = {
		users:[
			{id:'001',name:'tom',age:18},
			{id:'002',name:'jack',age:19},
			{id:'003',name:'peiqi',age:20},
		]
		// users:'abc'
	}

	render() {
		return (
			<div>
				<h2>我是Child组件</h2>
				{
					this.state.users.map((userObj)=>{
						return <h4 key={userObj.id}>{userObj.name}----{userObj.age}</h4>
					})
				}
			</div>
		)
	}
}

9. 组件通信方式总结

组件间的关系:
  • 父子组件
  • 兄弟组件(非嵌套组件)
  • 祖孙组件(跨级组件)
几种通信方式:
	1.props:
		(1).children props
		(2).render props
	2.消息订阅-发布:
		pubs-sub、event等等
	3.集中式管理:
		redux、dva等等
	4.context:
		生产者-消费者模式
比较好的搭配方式:
	父子组件:props
	兄弟组件:消息订阅-发布、集中式管理
	祖孙组件(跨级组件):消息订阅-发布、集中式管理、context(开发用的少,封装插件用的多)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值