React学习打卡Day07

1.插槽
        React支持在引入的组件内写html语句,在定义的组件内使用this.props.children取用
        有利于组件复用和减少父子间通信,预留插槽自己定义需要插入的语句

2.React生命周期
        1)初始化阶段
                Ⅰ.componentWillMount:render之前最后有一次修改状态的机会,初始化数据的作用
                Ⅱ.render:只能访问this.props和this.state,不允许修改状态和DOM输出
                Ⅲ.componentDiMount:成功render并渲染完成真实DOM之后触发,可以修改DOM
            可用于数据请求axios、订阅函数调用、setInterval、对创建完的dom进行初始化
        2)运行中阶段
                Ⅰ.componentWillReceiveProps:父组件修改属性触发,当父组件的状态更新时触发
            最先获得父组件传来的属性,可以利用属性进行ajax或者逻辑处理,例如把属性转成状态
                Ⅱ.shouldComponentUpdate:返回false会阻止render调用,手动控制render更新条件,如果setState后的值未发生变化则可以不更新,性能优化函数

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

class Box extends Component{
    render(){
        return(
            <li style={{width:"100px",height:"100px",border:this.props.current===this.props.index?
            "1px solid red":"1px solid gray",float:"left",boxSizing:"border-box"}}>
                </li>
        )
    }
    shouldComponentUpdate = (nextProps, nextState) => {
        //为什么不能直接修改状态,因为react使用prevState和nextState保存新老状态,直接修改状态会导致不可预期的错误
        if(this.props.current===this.props.index  || nextProps.current === nextProps.index){
            return true;
        }
        return false;
    }
}
export default class App extends PureComponent {
    state = {
        list:["00","01","02","03","04","05","06","07","08","09"],
        current:0
    }
    render() {
        return (
            <div>
                <input type="number" onChange={(evt)=>{
                        this.setState({
                            current:Number(evt.target.value)
                        })
                }} value={this.state.current}></input>
                <div style={{overflow:"hidden"}}>
                {
                    this.state.list.map((item,index)=>
                        <Box key={item} current={this.state.current} index={index}></Box>)
                }
                </div>
            </div>
        )
    }
}

                Ⅲ.componentWillUpdate:不能修改属性和状态,每setState一次走一次
                Ⅳ.render:只能访问this.props和this.state,不允许修改状态和DOM输出
                Ⅴ.componentDidUpdate:可以修改DOM,会执行多次,可通过prevProps和prevState进行传参,从而判断执行时机
        3)销毁阶段
                componentWillUnmount:在删除组件之前进行清理操作,比如计时器和事件监听器


版权声明:本文为Narcissus__原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。