React了解

95 阅读8分钟

安装和使用

npm i -g create-react-app
create-react-app my-app
cd my-app
npm start

简单Demo

<div id="example"></div>
<script type="text/babel">
  ReactDOM.render(
    <h1>Hello, world!</h1>,
    document.getElementById('example')
  );
</script>

ReactDOM.render接收两个参数,第一个是要渲染的数据,第二个是渲染的地方

传值

1.父传子

// 子组件sayHi.js
function SayHi(props) {
return (
    <div>
        <h2>你好啊{props.name}</h2>
        <h2>你好啊{props.name2}</h2>
    </div>
    )
}
export default SayHi
    
// 子组件sayHello.js
function SayHello(props) {
return (
    <div>
        <h2>你好啊{props.name}</h2>
    </div>
    )
}
export default SayHello
    
// 父组件
import SayHi from './sayHi'
import SayHello from './SayHello'
    
function App() {
    let obj = {
        name:'景天',
        name2:'雪见',
    }
    return (
        <div className="App">
            // 复杂传值
            <SayHi obj={obj} />
            // 简单传值
            <SayHello name="雪见" />
        </div>
    );
}
export default App;

2.子传父

第一种:父组件传递一个函数给子组件 缺点:如果有多层嵌套,需要一级一级的把函数往下传

// 父组件中内容
import React, { Component } from 'react'
import './index.scss'
import InputBox from './components/Input'
    
export default class TodoList extends Component {
    
    state = {
        list: [
            {id:1,name:'景天',isCheck:true},
            {id:2,name:'雪见',isCheck:true},
            {id:3,name:'徐长卿',isCheck:false},
            {id:4,name:'紫萱',isCheck:false},
            {id:5,name:'龙葵',isCheck:true}
        ]
    }
    
    // 父组件定义一个方法传给子组件,子组件在需要的时候触发这个函数,父组件拿到子组件传进来的值,进行自己需要的操作即可。
    addList = (obj) => {
        const newList = [obj,...this.state.list]
        this.setState({
            list: newList
        })
    }
    
    render() {
        const {list} = this.state
        const {addList} = this
        return (
            <div className="main">
                <InputBox addList={addList} />
            </div>
        )
    }
}

// 子组件中内容
import React from 'react'

export default class InputBox extends React.Component {

    // 子组件的按键事件触发
    handleAddList = (e)=> {
        if (e.keyCode !== 13 || e.target.value.trim() === '') return
        const tempObj = {id: new Date().getTime(),name: e.target.value, isCheck: false}
        // 把获取到的值放到父组件传递过来的函数中
        this.props.addList(tempObj)
        e.target.value = ''
    }

    render() {
        return (
            <input className="inputBox" type="text" placeholder="请输入" onKeyUp={this.handleAddList} />
        )
    }
}

第二种:pubsub-js

首先需要npm下载
npm install pubsub-js

// 父组件中内容
import React, { Component } from 'react'
import PubSub from 'pubsub-js'      // 引入pubsub-js

export default class TodoList extends Component {
    state = {
        list: [
            {id:1,name:'景天',isCheck:true},
            {id:2,name:'雪见',isCheck:true},
            {id:3,name:'徐长卿',isCheck:false},
            {id:4,name:'紫萱',isCheck:false},
            {id:5,name:'龙葵',isCheck:true}
        ]
    }

    componentDidMount() {
        // 使用pubsub订阅消息,名字为‘addlist’
        // msg: 返回的是名字,newObj:返回的是发布的数据
        PubSub.subscribe('addList',(msg,newObj) => {
            const newList = [newObj,...this.state.list]
            this.setState({
                list: newList
            })
        })
    }

    render() {
        const {list} = this.state
        return (
            <div className="main">
                <InputBox />
            </div>
        )
    }
}

// 子组件中内容
import React from 'react'
import PubSub from 'pubsub-js'      // 引入pubsub-js

export default class InputBox extends React.Component {

    handleAddList = (e)=> {
        if (e.keyCode !== 13 || e.target.value.trim() === '') return
        const tempObj = {id: new Date().getTime(),name: e.target.value, isCheck: false}
        // 使用pubsub,发布消息,名称是‘addlist’
        // tempObj是发布的数据
        PubSub.publish('addList',tempObj)
        e.target.value = ''
    }

    render() {
        return (
            <input className="inputBox" type="text" placeholder="请输入" onKeyUp={this.handleAddList} />
        )
    }
}

生命周期

简单介绍

  1. 挂载卸载过程
  1. 更新过程
  1. 新增两个生命周期

详细说明

React的生命周期从广义上分为三个阶段:挂载、渲染、卸载

因此可以把React的生命周期分为两类:挂载卸载过程和更新过程。

下图是旧生命周期图

旧生命周期图

下图是新生命周期图

新生命周期图

1.挂载卸载过程

1.1 constructor()

constructor()中完成了React数据的初始化,它接受两个参数:props和context,当想在函数内部使用这两个参数时,需使用super()传入这两个参数。 注意:只要使用了constructor()就必须写super(),否则会导致this指向错误。

1.2 componentWillMount()

componentWillMount()一般用的比较少,它更多的是在服务端渲染时使用。它代表的过程是组件已经经历了constructor()初始化数据后,但是还未渲染DOM时。

1.3 componentDidMount()

组件第一次渲染完成,此时dom节点已经生成,可以在这里调用ajax请求,返回数据setState后组件会重新渲染

1.4 componentWillUnmount()

在此处完成组件的卸载和数据的销毁。

  • clear你在组建中所有的setTimeout,setInterval

  • 移除所有组建中的监听 removeEventListener

  • 有时候我们会碰到这个warning:

Can only update a mounted or mounting component. This usually      means you called setState() on an unmounted component. This is a   no-op. Please check the code for the undefined component.

原因:因为你在组件中的ajax请求返回setState,而你组件销毁的时候,请求还未完成,因此会报warning

解决方法:

componentDidMount() {
    this.isMount === true
    axios.post().then((res) => {
    this.isMount && this.setState({   // 增加条件ismount为true时
      aaa:res
    })
})
}
componentWillUnmount() {
    this.isMount === false
}

2.更新过程

2.1 componentWillReceiveProps (nextProps)

  • 在接受父组件改变后的props需要重新渲染组件时用到的比较多
  • 接受一个参数nextProps
  • 通过对比nextProps和this.props,将nextProps的state为当前组件的state,从而重新渲染组件
componentWillReceiveProps (nextProps) {
    nextProps.openNotice !== this.props.openNotice&&this.setState({
        openNotice:nextProps.openNotice
    },() => {
      console.log(this.state.openNotice:nextProps)
      //将state更新为nextProps,在setState的第二个参数(回调)可以打         印出新的state
  })
}

2.2 shouldComponentUpdate(nextProps,nextState)

  • 主要用于性能优化(部分更新)
  • 唯一用于控制组件重新渲染的生命周期,由于在react中,setState以后,state发生变化,组件会进入重新渲染的流程,在这里return false可以阻止组件的更新
  • 因为react父组件的重新渲染会导致其所有子组件的重新渲染,这个时候其实我们是不需要所有子组件都跟着重新渲染的,因此需要在子组件的该生命周期中做判断

2.3 componentWillUpdate (nextProps,nextState)

shouldComponentUpdate返回true以后,组件进入重新渲染的流程,进入componentWillUpdate,这里同样可以拿到nextProps和nextState。

2.4 componentDidUpdate(prevProps,prevState)

组件更新完毕后,react只会在第一次初始化成功会进入componentDidmount,之后每次重新渲染后都会进入这个生命周期,这里可以拿到prevProps和prevState,即更新前的props和state。

2.5 render()

render函数会插入jsx生成的dom结构,react会生成一份虚拟dom树,在每一次组件更新时,在此react会通过其diff算法比较更新前后的新旧DOM树,比较以后,找到最小的有差异的DOM节点,并重新渲染。

3.新增两个生命周期

3.1 getDerivedStateFromProps(nextProps, prevState)

代替componentWillReceiveProps()。

老版本中的componentWillReceiveProps()方法判断前后两个 props 是否相同,如果不同再将新的 props 更新到相应的 state 上去。这样做一来会破坏 state 数据的单一数据源,导致组件状态变得不可预测,另一方面也会增加组件的重绘次数。

举个例子:

// before
componentWillReceiveProps(nextProps) {
  if (nextProps.isLogin !== this.props.isLogin) {
    this.setState({ 
      isLogin: nextProps.isLogin,   
    });
  }
  if (nextProps.isLogin) {
    this.handleClose();
  }
}

// after
static getDerivedStateFromProps(nextProps, prevState) {
  if (nextProps.isLogin !== prevState.isLogin) {
    return {
      isLogin: nextProps.isLogin,
    };
  }
  return null;
}

componentDidUpdate(prevProps, prevState) {
  if (!prevState.isLogin && this.props.isLogin) {
    this.handleClose();
  }
}

这两者最大的不同就是: 在 componentWillReceiveProps 中,我们一般会做以下两件事,一是根据 props 来更新 state,二是触发一些回调,如动画或页面跳转等。

I. 在老版本的 React 中,这两件事我们都需要在 componentWillReceiveProps 中去做。

II. 而在新版本中,官方将更新state与触发回调重新分配到了getDerivedStateFromProps 与componentDidUpdate中,使得组件整体的更新逻辑更为清晰。而且在getDerivedStateFromProps中还禁止了组件去访问this.props,强制让开发者去比较nextProps与prevState中的值,以确保当开发者用到getDerivedStateFromProps这个生命周期函数时,就是在根据当前的props来更新组件的state,而不是去做其他一些让组件自身状态变得更加不可预测的事情。

3.2 getSnapshotBeforeUpdate(prevProps, prevState)

代替componentWillUpdate。

常见的 componentWillUpdate 的用例是在组件更新前,读取当前某个 DOM 元素的状态,并在 componentDidUpdate 中进行相应的处理。

这两者的区别在于:

I. 在React开启异步渲染模式后,在render阶段读取到的DOM元素状态并不总是和commit阶段相同,这就导致在componentDidUpdate中使用componentWillUpdate中读取到的DOM元素状态是不安全的,因为这时的值很有可能已经失效了。

II. getSnapshotBeforeUpdate会在最终的render之前被调用,也就是说在getSnapshotBeforeUpdate中读取到的DOM元素状态是可以保证与componentDidUpdate中一致的。 此生命周期返回的任何值都将作为参数传递给componentDidUpdate()。

组件的函数式写法和类写法

类的写法

// 这是完整写法
import React from 'react'

class Event extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            num: 1
        }
        this.clickBtn = this.clickBtn.bind(this)
        this.changeVal = this.changeVal.bind(this)
    }

    clickBtn () {
        let newNum = this.state.num + 1
        this.setState({num:newNum})
    }

    changeVal(e) {
        this.setState({num:Number(e.target.value)})
    }

    render() {
        return (
            <div>
                <button onClick={this.clickBtn}>按钮</button><br />
                <input type="text" value={this.state.num} onChange={this.changeVal} />
                <div>{this.state.num}</div>
                <div>{this.props.propsNum}</div>
            </div>
        )
    }
}

export default Event

// 还有简写法
import React from 'react'

class Event extends React.Component {
    // state可以写在这里是因为类里面可以直接写赋值语句,会自动添加到实例对象上
    state = {
        num: 1
    }

    // 函数能直接写也是一样,相当于是一个赋值语句,但是这里必须使用箭头函数的形式,要是写一个function是不行的,因为箭头函数的this是没有指向的,会自动找其外侧的this作为自己的this使用
    clickBtn = () => {
        let newNum = this.state.num + 1
        this.setState({num:newNum})
    }

    changeValn = (e) => {
        this.setState({num:Number(e.target.value)})
    }

    render() {
        return (
            <div>
                <button onClick={this.clickBtn}>按钮</button><br />
                <input type="text" value={this.state.num} onChange={this.changeVal} />
                <div>{this.state.num}</div>
                <div>{this.props.propsNum}</div>
            </div>
        )
    }
}

export default Event

函数式写法

function SayHi(props) {
    return (
        <div>
            <h2>你好啊 {props.obj.name}</h2>
        </div>
        )
    
}

export default SayHi

注意事项

  1. 由于 JSX 就是 JavaScript,一些标识符像 class 和 for 不建议作为 XML 属性名。作为替代,React DOM 使用 className 和 htmlFor 来做对应的属性。
    理解:就是在JSX写的HTML(只是类似HTML)中,class不能直接使用,需要用className

  2. 注意,原生HTML元素名以小写字母开头,而自定义的React类名以大写字母开头,比如HelloMessage不能写成helloMessage。除此之外还需要注意组件类只能包含一个顶层标签,否则也会报错。
    理解:现在JSX的组件里面的代码,需要最外层有一个div包裹着,其次就是组件命名和原生HTML区分,因此要求都是大写开头,在引用的时候,使用的时候也都是要大写开头的。

    // 子组件sayHi.js
    function SayHi() {
        return (
            <div>
                <h2>你好啊</h2>
            </div>
        )
    }
    export default SayHi
    
    // 父组件
    import SayHi from './sayHi'
    
    function App() {
        return (
            <div className="App">
                <SayHi />
            </div>
        );
    }
    export default App;