【发布时间】:2020-10-15 12:48:03
【问题描述】:
我正在尝试更改基于类的组件以响应挂钩。您可以在其中比较之前和即将到来的道具,并找出差异来改变状态。
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]);
我尝试使用 with previous 但我得到的 prev 状态与当前状态相同?以及如何在 hooks 上实现与 componentWillReceiveProps 相同的功能。
【问题讨论】:
-
usePrevious的配方不使用依赖数组,因为您希望效果触发每个渲染。不确定这是否是问题的原因,但你也可以正确地遵循食谱,对吧? ??????????♂️ -
@DrewReese 我尝试将数组长度添加到 usePrevious 挂钩,但仍然没有结果,有什么正确使用配方的想法吗?
标签: reactjs react-hooks