React学习30(react扩展)

setState更新状态的2中方法

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

        1.stateChange为状态改变对象(该对象可以体现出状态的更改)

         2.callback是可选的回调函数,它在状态更新完毕,界面也更新后(render调用后)才被调用

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

        1.updater为返回stateChange对象的函数

         2.updater可以接收到state,props

        3.callback是可选的回调函数,它在状态更新完毕,界面也更新后(render调用后)才被调用

总结:

1.对象式的setState是函数式的setState的简写(语法糖)

 2.使用原则:

          1)如果新状态不依赖于原状态===>使用对象方式

         2)如果新状态依赖于原状态====>使用函数方式

         3)如果需要在setState()执行后获取最新的状态数据,要在第二个callback函数中获取

代码示例:

import React, { Component } from 'react'

export default class Demo extends Component {

  state = {count:0}

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

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

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

路由组件的lazyLoad(懒加载)

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

const Login = lazy(() =>import('@/pages/Login'))

通过Suspense>指定在加载得到路由打包文件前显示一个自定义的Loading界面

<Suspense fallback= {<h1>loading....</h1>}>
     <Route path= "/about" component={About}/>
     <Route path="/home" component={Home}/>
</Suspense>

代码示例
 

import React, { Component, lazy, Suspense } from 'react'
import { NavLink, Route} from 'react-router-dom'
// import Home from './Home'
// import About from './About'

//路由懒加载
const Home = lazy(() => {import('./Home')})
const About = lazy(() => {import('./About')})

export default class Demo extends Component {
  render() {
    return (
      <div>
        <div className="row">
          <div className="col-xs-offset-2 col-xs-8">
            <div className="page-header"><h2>Vue Router Demo</h2></div>
          </div>
        </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= {<h1>loading....</h1>}>
                <Route path= "/about" component={About}/>
                <Route path="/home" component={Home}/>
              </Suspense>
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

Hooks

1)React Hook/Hooks是什么?

Hook是React 16.8版本增加的新特性, 可以让你在函数组件中使用state以及其他的React特性

2)三个常用的Hook

1)State Hook:React.useState()//内部有两个参数,第一个是状态,第二个是更新状态的方法

2)Effect Hook:React.useEffect()//内部也有两个参数,第一个是函数(相当于componentDidMount

生命周期钩子和componentDidUpdate生命周期钩子的作用),第二个是数组,若数 组为空表示谁

都不监测,若数组内写谁就监测谁

3)Ref Hook:React.useRef()

 3)State Hook

(1)state hook让函数组件也可以有state状态,并进行状态数据的读写操作

(2)语法: const [xxx状态,操作状态的方法setXxx] = React.useState(initValue)

(3)uesState说明:

        参数:第一次初始化指定的值在内部做缓存

       返回值:包含两个元素的数组,第一个为内部函数当前状态值,第二个为更新状态值的函数

(4)setXxx的两种写法

       setXxxx(newValue):参数为非函数值,直接指定新的状态值,内部用其覆盖原来的状态

       setXxx(value => newValue):参数为函数,接收原来的状态值,返回新的状态值,内部用其

覆盖原来的状态值

4)Effect Hook

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

(2)React中的副作用操作:

        发ajax请求数据获取

       设置订阅/启动定时器

       手动更改真实DOM

(3)语法和说明:   

React.useEffect(() => {        //在此可以执行任何带副作用的操作
       return () => {//在组件卸载前执行
         //在此做一些收尾工作,比如清楚定时器,取消订阅
      }   }, [stateValue])//如果指定的是空,回调函数只会在第一次render()后执行

(4)可以把useEffect看做是如下三个函数的组合:

        componentDidMount()

        componentWillUpdate()

        componentWillUnmount()

5)Ref Hook

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

(2)语法:const refContainer = React.useRef()

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

代码示例

// 类式组件
// import React, { Component } from 'react'
// import ReactDOM from 'react-dom'
//  class Demo extends Component {

//   state = {count:0}

//   myRef = React.createRef()

//  add = () => {
//    this.setState(state => ({count:state.count+1}))
//  }

//  show = () => {
//    alert(this.myRef.current.value)
//  }

//  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>
//         <input type="text" ref={this.myRef}/>
//         <h2>当前求和为:{this.state.count}</h2>
//         <button onClick= {this.add}>点我+1</button>
//         <button onClick= {this.unmount}>点击卸载组件</button>
//         <button onClick={this.show}>点击提示数据</button>
//       </div>
//     )
//   }
// }


//函数式组件
import React from 'react'
import ReactDOM from 'react-dom'
function Demo() {

  const [count, setCount] = React.useState(0)
  // console.log(count, setCount);
  const myRef = React.useRef()

  React.useEffect(() => {
    let timer = setInterval(() => {
      setCount(count => count+1)
    }, 1000)
    return () => {
      clearInterval(timer)
    }
  }, [])

  function add() {
    //setCount(count+1) //第一种写法
    setCount(count => count+1)
  }

  function show() {
    alert(myRef.current.value)
  }

  function unmount() {
    ReactDOM.unmountComponentAtNode(document.getElementById('root'))
  }

  return (
    <div>
       <input type="text" ref= {myRef} />
       <h2>当前求和为:{count}</h2>
       <button onClick= {add}>点我+1</button>
       <button onClick= {unmount}>点击卸载组件</button>
       <button onClick= {show}>点我提示数据</button>
    </div>
  )
}

export default Demo

Fragment

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

使用:

<Fragment></Fragment>//标签里面只能写入key

<></>

代码示例:

import React, { Component, Fragment } from 'react'

export default class Demo extends Component {
  render() {
    return (
      <Fragment key= {1}>
        <input type="text" />
        <input type="text" />
      </Fragment>
    )
  }
}

context

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

理解:一种组件间通信方式,常用语祖组件与后代组件间的通信

使用:

(1)创建Context容器对象

const XxxContext = React.createContext()

(2)渲染子组件时,外面包裹xxxContext.provider,通过value属性给后代组件传递数据

<xxxContext.provider value= {数据}>
    子组件
</xxContext.provider>

(3)后代组件读取数据:   

//第一种方式:仅用于类组件
static contextType = xxxContext//声明接收context
this.context//读取context中的value值

//第二种方式:函数组件和类组件都可以使用

<xxxContext.Consumer>
      {        value => (//value就是context中的value数据
      要显示的内容
      )   }    </xxxContext.Consumer>

代码示例

import React, { Component } from 'react'
import './index.css'

//创建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'>
        <h2>我是A组件</h2>
        <h3>我的用户名是:{userName}</h3>
        {/* 传递多个状态数据可以写成对象的形式 */}
        <Provider value= {
   
   {userName, age}}>
          <B/>
        </Provider>
      </div>
    )
  }
}

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

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


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


组件优化

Component的2个问题

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

2.只当前组件重新render(),就会自动重新render()子组件,纵使子组件没有用到父组件的任何东西

===>效率低 效率高的做法: 只有当前组件的state和props发生改变时才重新render()

原因:

Component中的shouldComponentUpdate()总是返回true

解决:

办法1:

重写shouldComponentUpdate() 方法

   比较新旧state和props数据,如果有变化才返回true,如果没有返回fales

办法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:'奔驰C63'}

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

  // shouldComponentUpdate(nextProps, nextState){
  //   // console.log(this.props, this.state);
  //   // console.log(nextProps, nextState);
  //   if(this.state.carName === nextState.carName) return false
  //   else return true
  // }

  render() {
    console.log('Parent--render');
    const {carName} = this.state
    return (
      <div className='parent'>
        <h2>我是Parent组件</h2>
        <span>我的车名字是:{carName}</span><br/>
        <button onClick= {this.changeCar}>点我换车</button>
        <Child carName='奥拓'/>
      </div>
    )
  }
}

class Child extends PureComponent  {

  // shouldComponentUpdate(nextProps, nextState){
  //   console.log(this.props, this.state);
  //   console.log(nextProps, nextState);
  //   return !this.props.carName === nextProps.carName//简写形式
  //   // if(this.props.carName === nextProps.carName) return false
  //   // else return true
  // }

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

render props

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

vue中:

使用slot技术,也就是通过组件标签体传入结构A>B/>/A>

React中:

使用children props:通过组件标签体传入结构

   使用render props:通过组件标签属性传入结构,而且可以携带数据,一般用render函数属性

children props 

<A>
    <B>xxxxx</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'>
        <h2>我是parent组件</h2>
        <A render = {(name) => <B name = {name}/>}/>
      </div>
    )
  }
}

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

class B extends Component {
  render() {
    return (
      <div  className='b'>
        <h2>我是B组件,{this.props.name}</h2>
      </div>
    )
  }
}

边界错误

理解:

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

特点: 只能捕获后代组件生命周期产生的错误,不能捕获自己组件产生的错误和其他组件在合成

事件,定时器中产生的错误

使用方式:getDerivedStateFromError配合componentDidCatch

//生命周期函数,一旦后台组件报错,就会触发

static getDerivedStateFromError(error) {
    console.log(error)
    //在render之前触发
    //返回新的state
    return {
        hasError:true
   }
}
componentDidCatch(error,info) {
    //统计页面的错误,发送请求发送到后台去
    console.log(error,info)
}

代码示例:

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

组件通信方式总结

组件间的关系: 父子组件 兄弟组件(非嵌套组件) 祖孙组件(跨级组件)

几种通信方式:

1.props:

  (1)children props

  (2)render props

2.消息订阅-发布

pubs-sub、event等等

3.集中式管理

redux,dva等

4.conText

生产者--消费者模式

 比较好的搭配方式:

父子组件:props

兄弟组件:消息订阅--发布,集中式管理 祖孙组件(跨级组件):消息订阅--发布,集中式管理,

conText(开发用的少,封装插件用的多)

猜你喜欢

转载自blog.csdn.net/xiaojian044/article/details/128364035