React扩展

setState

setState更新状态的2种写法

1.setState(stateChange, [callback])------对象式的setState

  • stateChange为状态改变对象(该对象可以体现出状态的更改)
  • callback是可选的回调函数, 它在状态更新完毕、界面也更新后(render调用后)才被调用
export default class Demo extends Component {

	state = {count:0}

	add = ()=>{
		//对象式的setState
		//1.获取原来的count值
		const {count} = this.state
		//2.更新状态
		this.setState({count:count+1},()=>{
			console.log(this.state.count);
		})
		//console.log('12行的输出',this.state.count); //0 */

		//函数式的setState
		this.setState( state => ({count:state.count+1}))
	}

	render() {
		return (
			<div>
				<h1>当前求和为:{this.state.count}</h1>
				<button onClick={this.add}>点我+1</button>
			</div>
		)
	}
}

2.setState(updater, [callback])------函数式的setState

//函数式的setState
this.setState( state => ({count:state.count+1}))}
  • updater为返回stateChange对象的函数。
  • updater可以接收到state和props。
  • callback是可选的回调函数, 它在状态更新、界面也更新后(render调用后)才被调用。

总结:
1.对象式的setState是函数式的setState的简写方式(语法糖)
2.使用原则:

  • 如果新状态不依赖于原状态 ===> 使用对象方式
  • 如果新状态依赖于原状态 ===> 使用函数方式
  • 如果需要在setState()执行后获取最新的状态数据, 要在第二个callback函数中读取

lazyLoad

路由组件的lazyLoad

1.通过React的lazy函数配合import()函数动态加载路由组件 ===> 路由组件代码会被分开打包

import React, { Component,lazy,Suspense} from 'react'

const Home = lazy(()=> import('./Home') )
const About = lazy(()=> import('./About'))

2.通过<Suspense>指定在加载得到路由打包文件前显示一个自定义loading界面
Loading/index.jsx

import React, { Component } from 'react'

export default class Loading extends Component {
	render() {
		return (
			<div>
				<h1 style={{backgroundColor:'gray',color:'orange'}}>Loading....</h1>
			</div>
		)
	}
}

在组件中使用

<div className="row">
	<div className="col-xs-2 col-xs-offset-2">
		<div className="list-group">
			{/* 在React中靠路由链接实现切换组件--编写路由链接 */}
			<NavLink className="list-group-item" to="/about">About</NavLink>
			<NavLink className="list-group-item" to="/home">Home</NavLink>
		</div>
	</div>
	<div className="col-xs-6">
		<div className="panel">
			<div className="panel-body">
				<Suspense fallback={<Loading/>}>
					{/* 注册路由 */}
					<Route path="/about" component={About}/>
					<Route path="/home" component={Home}/>
				</Suspense>
			</div>
		</div>
	</div>
</div>

Hooks

Hook是React 16.8.0版本增加的新特性/新语法。可以让你在函数组件中使用 state 以及其他的 React 特性
三个常用的Hook

  • State Hook: React.useState()
  • Effect Hook: React.useEffect()
  • Ref Hook: React.useRef()

State Hook

State Hook让函数组件也可以有state状态, 并进行状态数据的读写操作。

语法: const [xxx, setXxx] = React.useState(initValue) ;

useState()说明:

  • 参数: 第一次初始化指定的值在内部作缓存
  • 返回值: 包含2个元素的数组, 第1个为内部当前状态值, 第2个为更新状态值的函数
function Demo(){
   const [count,setCount] = React.useState(0)
   	//加的回调
    function add(){
		//setCount(count+1) //第一种写法
		setCount(count => count+1 )
    }
   return (
   <div>
		<h2>当前求和为:{count}</h2>
		<button onClick={add}>点我+1</button>
	</div>
		)
}

setXxx()2种写法:(Xxx表示自定义更新状态值的函数名)

  • setXxx(newValue): 参数为非函数值, 直接指定新的状态值, 内部用其覆盖原来的状态值
  • setXxx(value => newValue): 参数为函数, 接收原本的状态值, 返回新的状态值, 内部用其覆盖原来的状态值

Effect Hook

Effect Hook 可以让你在函数组件中执行副作用(Effect)操作(用于模拟类组件中的生命周期钩子)

需求:进入页面count每隔一秒中加1,点击卸载组件按钮清除定时器

类组件实现

class Demo extends React.Component {
	state = {count:0}
	
	unmount = ()=>{
		ReactDOM.unmountComponentAtNode(document.getElementById('root'))
	}
	componentDidMount(){
		this.timer = setInterval(()=>{
			this.setState( state => ({count:state.count+1}))
		},1000)
	}
	componentWillUnmount(){
		clearInterval(this.timer)
	}
	render() {
		return (
			<div>
				<h2>当前求和为{this.state.count}</h2>
			</div>
			<button onClick={this.unmount}>卸载组件</button>
		)
	}
}

函数组件实现

React中的副作用操作:

  • 发ajax请求数据获取
  • 设置订阅 / 启动定时器
  • 手动更改真实DOM
语法和说明: 
React.useEffect(() => { 
	  // 相对与componentDidMount()和componentDidUpdate(),具体相当与那个钩子函数,由第二个参数决定
      // 在此可以执行任何带副作用操作
      return () => { // 在组件卸载前执行
         // componentWillUnmount() 
        // 在此做一些收尾工作, 比如清除定时器/取消订阅等
      }
    }, [stateValue]) // 如果指定的是[], 回调函数只会在第一次render()后执行

可以把 useEffect Hook 看做如下三个函数的组合

  • componentDidMount()
  • componentDidUpdate()
  • componentWillUnmount()
function Demo(){
	//React.useState()
    const [count,setCount] = React.useState(0)
	
	// 	React.useEffect()
   	React.useEffect(()=>{
		let timer = setInterval(()=>{
			setCount(count => count+1 )
		},1000)
		return ()=>{
			clearInterval(timer)
		}
	},[])
    //加的回调
    function add(){
		//setCount(count+1) //第一种写法
		setCount(count => count+1 )
    }
    
    //卸载组件的回调
	function unmount(){
		ReactDOM.unmountComponentAtNode(document.getElementById('root'))
	}
   return (
   <div>
		<h2>当前求和为:{count}</h2>
		<button onClick={add}>点我+1</button>
		<button onClick={unmount}>卸载组件</button>
	</div>
		)
}

Ref Hook

Ref Hook可以在函数组件中存储/查找组件内的标签或任意其它数据

语法: const refContainer = useRef()

function Demo(){
	const myRef = React.useRef()
   
    //提示输入的回调
	function show(){
		alert(myRef.current.value)
	}
	
	return (
		<div>
			<input type="text" ref={myRef}/>
			<button onClick={show}>点我提示数据</button>
		</div>
	)
}

作用: 保存标签对象,功能与React.createRef()一样

Fragment

可以不用必须有一个真实的DOM根标签了,使用<Fragment>组件包裹标签,React会把Fragment清除

<Fragment>
  	<input type="text"/>
    <input type="text"/>
<Fragment>
或者
<>
	<input type="text"/>
	<input type="text"/>
</>

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对象
const MyContext = React.createContext()
const {Provider,Consumer} = MyContext
export default class A extends Component {

	state = {username:'tom',age:18}

	render() {
		const {username,age} = this.state
		return (
			<div className="parent">
				<h3>我是A组件</h3>
				<h4>我的用户名是:{username}</h4>
				<Provider value={{username,age}}>
					<B/>
				</Provider>
			</div>
		)
	}
}

class B extends Component {
	render() {
		return (
			<div className="child">
				<h3>我是B组件</h3>
				<C/>
			</div>
		)
	}
}

/* class C extends Component {
	//声明接收context
	static contextType = MyContext
	render() {
		const {username,age} = this.context
		return (
			<div className="grand">
				<h3>我是C组件</h3>
				<h4>我从A组件接收到的用户名:{username},年龄是{age}</h4>
			</div>
		)
	}
} */

function C(){
	return (
		<div className="grand">
			<h3>我是C组件</h3>
			<h4>我从A组件接收到的用户名:
			<Consumer>
				{value => `${value.username},年龄是${value.age}`}
			</Consumer>
			</h4>
		</div>
	)
}

render props

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

Vue中:

  • 使用slot技术, 也就是通过组件标签体传入结构 <AA><BB/></AA>

React中:

  • 使用children props: 通过组件标签体传入结构
  • 使用render props: 通过组件标签属性传入结构, 一般用render函数属性

children props

class A extends Component {
	render() {
		return (
			<div className="a">
				<h3>我是A组件</h3>
				<B>Hello</B>
			</div>
		)
	}
}


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

render props

<A render={(data) => <B data={data}></B>}></A>
A组件: {this.props.render(内部state数据)}
B组件: 读取A组件传入的数据显示 {this.props.data} 

错误边界

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

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

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

只适用于生产环境,及打包并后的项目,如果不是打包的的项目,即使显示错误边界子组件的信息也会马上显示全部错误信息

组件通信方式

props:
	(1).children props
	(2).render props
消息订阅-发布:
	pubs-sub、event等等
集中式管理:
	redux、dva等等
conText:
	生产者-消费者模式

组件间的关系

父子组件:props
兄弟组件(非嵌套组件):消息订阅-发布、集中式管理
祖孙组件(跨级组件):消息订阅-发布、集中式管理、conText(用的少)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李熠漾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值