如何使用 React Hook for componentWillReceiveProps



>我正在尝试将基于类的组件更改为反应钩子。 在这里您可以比较以前和即将推出的道具并找到差异以改变状态。

class_component

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]);

我尝试使用以前的状态,但我得到的上一个状态与当前状态相同? 以及如何在钩子上实现组件将接收道具的相同功能。

使用 React Hook for componentWillReceiveProps 像这样

useEffect( () => {
console.log('posts updated');
},
[props.posts])

相关内容

  • 没有找到相关文章

最新更新