【问题标题】:how to use React Hook for componentWillReceiveProps如何将 React Hook 用于 componentWillReceiveProps
【发布时间】: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


【解决方案1】:

可以像这样使用 React Hook for componentWillReceiveProps

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

【讨论】:

  • 虽然此代码可以解决 OP 的问题,但最好包含关于您的代码如何解决 OP 问题的说明。通过这种方式,未来的访问者可以从您的帖子中学习,并将其应用到他们自己的代码中。 SO 不是编码服务,而是知识资源。此外,高质量、完整的答案更有可能得到支持。这些功能,以及所有帖子都是独立的要求,是 SO 作为一个平台的一些优势,使其与论坛区分开来。您可以编辑以添加其他信息和/或使用源文档补充您的解释。
  • @Kavesh useEffect 将根据较新的道具而改变,但我试图与以前的道具和传入的道具有所不同。但无法实现。有时对每个生命周期方法使用 useEffect 仍然让我无法正确使用它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 2022-12-21
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
相关资源
最近更新 更多