React学习打卡Day07

本文探讨了React中如何通过this.props.children实现组件插槽,以提高代码复用。同时,详细阐述了React组件的生命周期,包括初始化、运行中和销毁阶段的关键方法,如componentWillMount、shouldComponentUpdate等,以及它们在性能优化和数据处理中的作用。

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:在删除组件之前进行清理操作,比如计时器和事件监听器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值