71

tldr; 如何模拟componentDidUpdate或以其他方式使用key带有数组的道具来强制重置我的组件?

我正在实现一个组件,它显示一个计时器并在它达到零时执行一个回调。目的是让回调更新对象列表。后一个组件由新的React hooks useStateuseEffect.

state包含对计时器启动时间和剩余时间的引用。设置每秒调用一次的effect间隔来更新剩余时间,并检查是否应该调用回调。

该组件不打算重新安排计时器,或者在达到零时保持间隔,它应该执行回调并空闲。为了让计时器刷新,我希望将一个数组传递给key它会导致组件的状态被重置,因此计时器将重新启动。不幸的是key必须与字符串一起使用,因此无论我的数组的引用是否已更改都不会产生任何影响。

我还尝试通过传递我关心的数组来将更改推送到道具,但状态保持不变,因此间隔没有重置。

观察数组中的浅变化以强制仅使用新的钩子 API 更新状态的首选方法是什么?

import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';

function getTimeRemaining(startedAt, delay) {
    const now = new Date();
    const end = new Date(startedAt.getTime() + delay);
    return Math.max(0, end.getTime() - now.getTime());
}

function RefresherTimer(props) {
    const [startedAt, setStartedAt] = useState(new Date());
    const [timeRemaining, setTimeRemaining] = useState(getTimeRemaining(startedAt, props.delay));

    useEffect(() => {

        if (timeRemaining <= 0) {
            // The component is set to idle, we do not set the interval.
            return;
        }

        // Set the interval to refresh the component every second.
        const i = setInterval(() => {
            const nowRemaining = getTimeRemaining(startedAt, props.delay);
            setTimeRemaining(nowRemaining);

            if (nowRemaining <= 0) {
                props.callback();
                clearInterval(i);
            }
        }, 1000);

        return () => {
            clearInterval(i);
        };
    });

    let message = `Refreshing in ${Math.ceil(timeRemaining / 1000)}s.`;
    if (timeRemaining <= 0) {
        message = 'Refreshing now...';
    }

    return <div>{message}</div>;
}

RefresherTimer.propTypes = {
    callback: PropTypes.func.isRequired,
    delay: PropTypes.number
};

RefresherTimer.defaultProps = {
    delay: 2000
};

export default RefresherTimer;

尝试使用key

<RefresherTimer delay={20000} callback={props.updateListOfObjects} key={listOfObjects} />

尝试与道具更改一起使用:

<RefresherTimer delay={20000} callback={props.updateListOfObjects} somethingThatChanges={listOfObjects} />

listOfObjects指的是一个对象数组,其中对象本身不一定会改变,所以该数组应该与!==. 通常,该值将来自Redux,其中该操作updateListOfObjects会导致数组重新初始化,如下所示newListOfObjects = [...listOfObjects]

4

6 回答 6

125

useRef功能组件中创建一个“实例变量”。它作为一个标志来指示它是否处于挂载或更新阶段而不更新状态。

const mounted = useRef();
useEffect(() => {
  if (!mounted.current) {
    // do componentDidMount logic
    mounted.current = true;
  } else {
    // do componentDidUpdate logic
  }
});
于 2018-11-21T06:27:30.833 回答
9

简而言之,您想在数组的引用更改时重置计时器,对吗?如果是这样,您将需要使用一些差异机制,纯基于钩子的解决方案将利用 的第二个参数useEffect,如下所示:

function RefresherTimer(props) {
  const [startedAt, setStartedAt] = useState(new Date());
  const [timeRemaining, setTimeRemaining] = useState(getTimeRemaining(startedAt, props.delay));

  //reset part, lets just set startedAt to now
  useEffect(() => setStartedAt(new Date()),
    //important part
    [props.listOfObjects] // <= means: run this effect only if any variable
    // in that array is different from the last run
  )

  useEffect(() => {
    // everything with intervals, and the render
  })
}

有关此行为的更多信息https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

于 2018-11-16T12:36:37.907 回答
6

使用自定义钩子

export const useComponentDidUpdate = (effect, dependencies) => {
  const hasMounted = useRef(false);

  useEffect(
    () => {
      if (!hasMounted.current) {
        hasMounted.current = true;
        return;
      }
      effect();
    }, 
    dependencies
  );
};

初始渲染后效果不会运行。此后,它取决于应观察的值数组。如果它是空的,它将在每次渲染后运行。否则,它将在其值之一发生更改时运行。

于 2019-12-24T12:38:38.287 回答
1

先创建钩子

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  }, [value]);
  return ref.current;
}

现在在主要功能

import React, {useEffect, useState} from 'react';
import {Text, View} from 'react-native';
import usePrevious from './usePrevious';

export default function Example() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);
  

  useEffect(() => {
    // this one is your didupdate method for count variable
    if (count != prevCount) {
      alert('count updated')
    }
  }, [count]);



  return (
    <View>
      <Text>
        You clicked {count} times {prevCount}{' '}
      </Text>
      
      <Text onPress={() => setCount(count + 1)}>Increment</Text>

      <Text onPress={() => setCount(count - 1)}>Decrement</Text>
    </View>
  );
}
于 2021-02-22T09:50:55.730 回答
0

You can use useUpdateEffect from react-use.

于 2021-06-28T13:16:09.910 回答
-1

重新安装组件的一种方法是提供新key属性。它不一定是字符串,但会在内部强制转换为字符串,因此如果listOfObjects是字符串,则应在key内部与listOfObjects.toString().

可以使用任何随机密钥,例如uuidMath.random()listOfObjects可以在父组件中进行浅比较以提供新的密钥。useMemohook 可以在 parent 状态下用于有条件地更新 remount key,listOfObjects也可以作为需要记忆的参数列表。这是一个例子

  const remountKey = useMemo(() => Math.random(), listOfObjects);

  return (
    <div>
      <RefresherTimer delay={3000} callback={() => console.log('refreshed')} key={remountKey} />
    </div>
  );

作为重新挂载键的替代方案,子组件可以重置自己的状态并公开回调以触发重置。

对内部子组件进行浅层比较listOfObjects将是一种反模式,因为这需要它了解父组件的实现。

于 2018-11-12T09:11:53.773 回答