react实现computed和watch

类组件

1. componentDidUpdate可以实现两者

2. getter方法可以实现computed
get address() {
    const { province, city } = this.state;
    return `${province} ${city}`;
}
getter没有缓存,要加缓存,即属性变化才触发重新计算,需引入额外的memoize包
getAddress = memoize((province, city) => `${province} ${city}`);

get address() {
    return this.getAddress(this.state.province, this.state.city);
}
函数式组件

1. useMemo实现computed
useMemo(() => {
    return `${province}省${city}市`
}, [province, city]);
2. useEffect实现watch
useEffect(() => {
    console.log('province或city发生了变化: ', province, city);
}, [province, city]);
posted @ 2022-04-22 14:06  全玉  阅读(1238)  评论(0编辑  收藏  举报