# 控制 render 的方法
# 缓存 element 对象
import React from 'react';
function Child() {
console.log('child render');
return 'child';
}
export default class Home extends React.Component {
state = {
a: 0,
b: 0
};
render() {
return (
<div>
<Child a={this.state.a} />
<button onClick={() => this.setState({ a: this.state.a + 1 })}>a - {this.state.a}</button>
<button onClick={() => this.setState({ b: this.state.b + 1 })}>b - {this.state.b}</button>
</div>
);
}
}
改进:
import React from 'react';
function Child() {
console.log('child render');
return 'child';
}
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
a: 0,
b: 0
};
// 缓存
this.cacheCmp = <Child a={this.state.a} />;
}
controllCmpRender = () => {
const { props } = this.cacheCmp;
if (props.a !== this.state.a) this.cacheCmp = React.cloneElement(this.cacheCmp, { a: this.state.a });
return this.cacheCmp;
};
render() {
return (
<div>
{this.controllCmpRender()}
<button onClick={() => this.setState({ a: this.state.a + 1 })}>a - {this.state.a}</button>
<button onClick={() => this.setState({ b: this.state.b + 1 })}>b - {this.state.b}</button>
</div>
);
}
}
使用useMemo进行缓存
import React, { useMemo, useState } from 'react';
function Child() {
console.log('child render');
return 'child';
}
export default () => {
const [ a, setA ] = useState(0);
const [ b, setB ] = useState(0);
// 返回的是一个 memoized 值
const CacheCmp = useMemo(() => <Child a={a} />, [ a ]);
return (
<div>
{CacheCmp}
<button onClick={() => setA(a + 1)}>a - {a}</button>
<button onClick={() => setB(b + 1)}>b - {b}</button>
</div>
);
};