仅当两个依赖项都发生变化时才运行 Effect 钩子 [英] Run Effect hook only when both dependencies change

查看:51
本文介绍了仅当两个依赖项都发生变化时才运行 Effect 钩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 React 组件,它使用 useEffect 钩子获取数据,如下所示:

const cache = {key: "data-fetched-using-key"}功能配置({键,选项}){const [数据,setData] = useState();useEffect(() => {const fetchedData;//使用键和选项获取数据设置数据(获取数据);缓存[键] = fetchedData;}, [键, 选项])返回<p>{数据}</p>;}

每次 keyoptions 更改时都会运行钩子.但是,我也在本地缓存数据,并且只希望在 keyoptions 更改时运行效果(因为对于每个键/选项组合,数据将始终是一样的).

是否有一种干净的方法来依赖 key AND options 而不是 key OR options 的组合使用 React Hooks?

解决方案

您可以使用 useRef() 创建这种逻辑.考虑以下示例和沙箱:https://codesandbox.io/s/react-hooks-useeffect-with-multiple-reqs-6ece5

const App = () =>{const [name, setName] = useState();const [age, setAge] = useState();const previousValues = useRef({ name, age });useEffect(() => {如果 (previousValues.current.name !== name &&previousValues.current.age !== 年龄){//你的逻辑在这里console.log(name + " " + age);控制台日志(previousValues.current);//然后将previousValues更新为当前值previousValues.current = { name, age };}});返回 (<div><输入占位符=名称"值={名称}onChange={e =>setName(e.target.value)}/><输入占位符=年龄"价值={年龄}onChange={e =>setAge(e.target.value)}/>

);};

工作流程:

  1. 我们为要跟踪的两个值创建一个 ref 对象,在这种情况下,它是一个 nameage.ref 对象是 previousValues.
  2. useEffect 已定义,但我们不为其提供任何依赖项.相反,只要有状态改变,我们就让它执行nameage.
  3. 现在在 useEffect 中,我们有条件逻辑来检查nameage 的先前/初始值都不同于它们对应的状态值.如果他们很好,我们就执行我们的逻辑(console.log).
  4. 最后在执行逻辑后,将引用对象 (previousValues) 更新为当前值 (state).

I have a React component that fetches data using the useEffect hook like so:

const cache = {key: "data-fetched-using-key"}
function Config({key, options}) {
    const [data, setData] = useState();
    useEffect(() => {
        const fetchedData; // fetch data using key and options
        setData(fetchedData);
        cache[key] = fetchedData;
    }, [key, options])
    return <p>{data}</p>;
}

This runs the hook every time key or options change. However, I'm also caching the data locally, and only want the effect to run when both key AND options change (since for each key/options combination the data will always be the same).

Is there a clean way to depend on the combination of key AND options rather than key OR options using React Hooks?

解决方案

You can create this sort of logic with useRef(). Consider the following example and sandbox: https://codesandbox.io/s/react-hooks-useeffect-with-multiple-reqs-6ece5

const App = () => {
  const [name, setName] = useState();
  const [age, setAge] = useState();

  const previousValues = useRef({ name, age });

  useEffect(() => {
    if (
      previousValues.current.name !== name &&
      previousValues.current.age !== age
    ) {
      //your logic here
      console.log(name + " " + age);
      console.log(previousValues.current);

      //then update the previousValues to be the current values
      previousValues.current = { name, age };
    }
  });

  return (
    <div>
      <input
        placeholder="name"
        value={name}
        onChange={e => setName(e.target.value)}
      />
      <input
        placeholder="age"
        value={age}
        onChange={e => setAge(e.target.value)}
      />
    </div>
  );
};

Workflow:

  1. We create a ref object for the two values we want to keep track of, in this case its a name and age. The ref object is previousValues.
  2. useEffect is defined but we do not provide it any dependencies. Instead, we just have it execute whenever there is a state-change to name or age.
  3. Now inside useEffect we have conditional logic to check whether the previous/initial values of both name and age are different than their corresponding state-values. If they are then good we execute our logic (console.log).
  4. Lastly after executing the logic, update the ref object (previousValues) to the current values (state).

这篇关于仅当两个依赖项都发生变化时才运行 Effect 钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆