![](/img/trans.png)
[英]componentWillReceiveProps, componentDidUpdate for React Hook
[英]how to use React Hook for componentWillReceiveProps
我正在尝试更改基于 class 的组件以响应挂钩。 您可以在其中比较以前和即将推出的道具,并找出差异来变异 state。
类组件
componentWillReceiveProps(props) {
if (
props.artistState.nextVideos.length >
this.props.artistState.nextVideos.length
) {
const diff =
props.artistState.nextVideos.length -
this.props.artistState.nextVideos.length
this.setState(state => {
return { loadingItems: state.loadingItems - diff }
})
}
}
挂钩
function usePrevious(value) {
// The ref object is a generic container whose current property is mutable ...
// ... and can hold any value, similar to an instance property on a class
const ref = useRef();
// Store current value in ref
useEffect(() => {
ref.current = value;
}, [value]); // Only re-run if value changes
// Return previous value (happens before update in useEffect above)
return ref.current;
}
const prevVideosLen = usePrevious(artistState.nextVideos.length);
useEffect(() => {
if (prevVideosLen) {
console.log('artist:: Card', {
length1: artistState.nextVideos.length,
length2: prevVideosLen,
});
if (artistState.nextVideos.length > prevVideosLen) {
const diff = artistState.nextVideos.length - prevVideosLen;
console.log('artist:: Card', { diff });
setLoadingItems((prev) => prev - diff);
}
}
}, [artistState, prevVideosLen]);
我尝试与以前一起使用,但我得到的上一个 state 与当前的相同? 以及如何在挂钩上实现与 componentWillReceiveProps 相同的功能。
像这样使用可以 React Hook for componentWillReceiveProps
useEffect( () => {
console.log('posts updated');
},
[props.posts])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.