当前位置:首页 > 编程笔记 > 正文
已解决

react之Component存在的2个问题

来自网友在路上 166866提问 提问时间:2023-11-09 13:23:34阅读次数: 66

最佳答案 问答题库668位专家为你答疑解惑

问题

  • 只要执行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;
}

效果实现:
在这里插入图片描述

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"react之Component存在的2个问题":http://eshow365.cn/6-36230-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!