react之Component存在的2个问题

编程入门 行业动态 更新时间:2024-10-26 23:36:47

<a href=https://www.elefans.com/category/jswz/34/1771383.html style=react之Component存在的2个问题"/>

react之Component存在的2个问题

问题

  • 只要执行setState(),即使不改变状态数据,组件也会重新render()
  • 只当前组件重新render(),就会自动重新render子组件

原因

  • Component中的shouldComponentUpdate()总是返回true

思路

  • 只有当组件的state或props数据发生改变时才重新render()

解决

  • 重写shouldComponentUpdate()方法:比较新旧state或props数据,如果有变化才返回true,如果没有返回false
  • 使用PureComponent:PureComponent重写了shouldComponentUpdate()方法,只有state或props数据有变化才返回true。(只进行state和props数据的浅比较,如果只是数据对象数据变了,返回false)

案例

import React, { PureComponent } from 'react'
import './index.css'export default class Parent extends PureComponent {state = { carName: '奔驰' }changeCar = ()=>{this.setState({carName:'五菱'})}// shouldComponentUpdate(nextProps,nextState){//     console.log('this.state:',this.state,'this.props:',this.props,'nextProps:',nextProps,'nextState:',nextState);//     return !(this.state.carName === nextState.carName)// }render() {console.log('Parent-render');const { carName } = this.statereturn (<div className='parent'><h5>parent组件</h5><span>我的车是:{carName}</span>&nbsp;&nbsp;&nbsp;<button onClick={this.changeCar}>换车</button><Child car='木马'></Child></div>)}
}class Child extends PureComponent {// shouldComponentUpdate(nextProps,nextState){//     console.log('this.state:',this.state,'this.props:',this.props,'nextProps:',nextProps,'nextState:',nextState);//     return !(this.props.car === nextProps.car)// }render() {console.log('Child-render');return (<div className='child'><h5>child组件</h5><div>Child组件从Parent组件拿到的车是:{this.props.car}</div></div>)}
}	

样式文件:

.parent{width: 500px;background-color: aqua;padding: 20px;
}.child{width: 90%;background-color:bisque;padding: 20px;margin-top: 30px;
}

效果实现:

更多推荐

react之Component存在的2个问题

本文发布于:2023-11-15 20:22:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1605767.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:react   Component

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!