如何在数组依赖中正确使用 useEffect 钩子。我从 redux 商店传递了状态,但我的组件仍然无限渲染

IT技术 javascript reactjs react-native redux react-hooks
2021-05-02 19:34:13

我正在使用 useEffect 钩子并使用函数getStoreUsers获取带有 fetch 调用的用户数据列表,函数在响应上调度操作并将shopUsers(这是一个数组)存储在 redux 存储中。

在数组依赖项中,我正在编写[shopUsers]我不知道为什么它会导致无限渲染。

这是我如何使用 useEffect 钩子:

useEffect(() => {
    const { getStoreUsers, shopUsers } = props;
    setLoading(true);
    getStoreUsers().then(() => {
      setLoading(false);
    }).catch(() => {
      setLoading(false);
    });
  }, [shopUsers]);

我只想在 shopUsers 数组中的数据发生更改时重新渲染组件。

如果我在数组依赖项中写入 shopUsers.length。它停止重新渲染。

但是,让我们假设我有一个页面,当用户单击 userList 并在下一页更新用户数据时,该页面会打开。更新后,我希望用户返回到以前未卸载的相同组件。因此,在这种情况下,数组长度保持不变,但更新了数组索引中的数据。所以 shopUsers.length 在这种情况下不起作用。

2个回答

您可以制作自定义挂钩来执行您想要的操作:

在本例中,我们替换数组中的最后一个元素,并在控制台中查看输出。

import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";
import { isEqual } from "lodash";

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

const App = () => {
  const [arr, setArr] = useState([2, 4, 5]);
  const prevArr = usePrevious(arr);

  useEffect(() => {
    if (!isEqual(arr, prevArr)) {
      console.log(`array changed from ${prevArr} to ${arr}`);
    } 
  }, [prevArr]);

  const change = () => {
    const temp = [...arr];
    temp.pop();
    temp.push(6);
    setArr(temp);
  };

  return (
      <button onClick={change}>change last array element</button>
  )
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

活生生的例子在这里

您的效果是基于“shopUsers”props触发的,它本身会触发更新“shopUsers”props的 redux 操作,这就是它无限触发的原因。

我认为您想要优化的是组件本身的渲染,因为您已经在使用 redux,我假设您的 props/state 是不可变的,因此您React.memo只能在组件之一时使用它来重新渲染您的组件改变。

此外,您应该在钩子之外定义 state/props 变量,因为它们像这样在整个函数的范围内使用。

在你的情况下,如果你将一个空数组作为第二个参数传递给备忘录,那么它只会在 ComponentDidMount 上触发,如果你传递 null/undefined 或不传递任何东西,它将在 ComponentDidMount + ComponentDidUpdate 上触发,如果你想优化即使props更改/组件更新,钩子也不会触发,除非特定变量发生更改,然后您可以添加一些变量作为第二个参数

React.memo(function(props){
  const [isLoading, setLoading] = useState(false);
  const { getStoreUsers, shopUsers } = props;
  useEffect(() => {
    setLoading(true);
    getStoreUsers().then(() => {
      setLoading(false);
    }).catch((err) => {
      setLoading(false);
    });
  }, []);
...
})