1.纯组件说明:
- import React from 'react';
- import ReactDOM from 'react-dom';
- // import MyEditor from './components/MyEditor';
-
- class App extends React.PureComponent{
- state={
- number:0
- }
- handleClick = () =>{
- this.setState(()=>{
- return{
- number: Math.floor(Math.random()*3)
- }
-
- })
- }
-
-
-
- render(){
- console.log('重新渲染')
- return(
- <div>
- <h1>随机数:{this.state.number}h1>
- <button onClick={this.handleClick}>重新生成button>
- div>
- )
- }
- }
引用类型的比较:(因为两者的地址一样,无论怎样点击按钮,都不会进行渲染)
- class App extends React.PureComponent{
- state={
- obj:{
- number:0
- }
- }
- handleClick = () =>{
- //错误演示
- const newObj = this.state.obj
- newObj.number = Math.floor(Math.random()*3)
- this.setState(()=>{
- return{
- obj:newObj
- }
-
- })
- }
-
-
-
- render(){
- console.log('重新渲染')
- return(
- <div>
- <h1>随机数:{this.state.obj.number}h1>
- <button onClick={this.handleClick}>重新生成button>
- div>
- )
- }
- }
正确演示:
- handleClick = () =>{
- //正确演示
- const newObj = {...this.state.obj,number:2}
- newObj.number = Math.floor(Math.random()*3)
- this.setState(()=>{
- return{
- obj:newObj
- }
-
- })
- }
