React进阶篇(十)性能优化
hello
)
}
// good
const style = {color: 'red'}
...
render(){
return (hello
)
}
利用shouldComponentUpdate优化更新条件
适当时使用React.PureComponent,其自带shouldComponentUpdate优化,会对props进行浅比较。
class Comp extends React.Component {
render(){
return ({this.props.name}
)
}
}
函数组件可以利用React.memo实现shouldComponentUpdate优化,同样是浅比较。
const MyComponent = React.memo(props => {
/* render using props */
return (
{props.name}
);
});
利用useMemo缓存复杂计算的值,利用useCallback缓存函数
// useMemo
// 使用useMemo来执行昂贵的计算,然后将计算值返回,并且将count作为依赖值传递进去。
// 这样,就只会在count改变的时候触发expensive执行,在修改val的时候,返回上一次缓存的值。
export default function WithMemo() {
const [count, setCount] = useState(1);
const [val, setValue] = useState('');
const expensive = useMemo(() => {
console.log('compute');
let sum = 0;
for (let i = 0; i < count * 100; i++) {
sum += i;
}
return sum;
}, [count]);
return {count}-{expensive}
{val}
setValue(event.target.value)}/>
{count}
setVal(event.target.value)}/>
{count}
}
React官方建议把state当作不可变对象。当组件的状态都是不可变对象时,shouldComponentUpdate只需浅比较就可以判断状态是否真的改变,从而避免不必要的render调用。
状态类型是不可变类型 - number, string, boolean, null, undefined
状态类型是array,创建新的数组返回(concat, slice, filter, map 会返回一个新数组):
// add
this.setState({
books: [...preState.books, 'New book']
})
// remove
this.setState({
books: preState.books.slice(1, 3)
})
// filter
this.setState({
books: preState.books.filter(item=>item !== 'React)
})
状态类型是object,创建新的对象返回(Object.assign,对象扩展语法,或者Immutable库)
this.setState({
owner: Object.assgin({}, preState.owner, {name: 'Jason'})
})
this.setState({
owner: {...preState.owner, name: 'Jason'}
})
微信公众号:

发表评论 (审核通过后显示评论):