实现指定组件进行渲染
- 使用shouldComponentUpdate实现指定组件渲染
import React, { Component} from 'react';
class Foo extends Component{
shouldComponentUpdate(nextProps,nextState){
if(nextProps.name===this.props.name){
return false;
}
return true
}
render(){
console.log('Foo render')
return <div>{this.props.person.age}</div>;
}
}
class App extends Component {
state = {
count: 0,
person: {
age: 1
}
}
callback = () => {
}
render() {
const { person } = this.state
return (
<div>
{}
<button onClick={() => {
person.age++;
this.setState({ count: this.state.count + 1 })
}}>
add
</button>
{}
{}
{}
<Foo person={person} cb={this.callback} />
</div>
)
}
}
export default App;
import React, { Component, PureComponent, memo } from 'react';
class Foo extends PureComponent{
render(){
console.log('Foo render')
return <div>{this.props.person.age}</div>;
}
}
class App extends Component {
state = {
count: 0,
person: {
age: 1
}
}
callback = () => {
}
render() {
const { person } = this.state
return (
<div>
{}
<button onClick={() => {
person.age++;
this.setState({ count: this.state.count + 1 })
}}>
add
</button>
{}
{}
{}
<Foo person={person} cb={this.callback} />
</div>
)
}
}
export default App;
import React, { Component, memo } from 'react';
const Foo = memo(function Foo(props) {
console.log('Foo render')
return <div>{props.person.age}</div>;
})
class App extends Component {
state = {
count: 0,
person: {
age: 1
}
}
callback = () => {}
render() {
const { person } = this.state
return (
<div>
{}
<button onClick={() => {
person.age++;
this.setState({ count: this.state.count + 1 })
}}>
add
</button>
{}
{}
{}
<Foo person={person} cb={this.callback} />
</div>
)
}
}
export default App;