我有一个带有依赖数组的UseEffect挂钩.

问题是,当我重新加载页面时,里面的代码运行every次.

我已经打印了这些值,所以它们不应该改变.

以下是其中的诱因:

  useEffect(
    function () {
      console.log('This prints on page load every time');
      // Check if the user is upvoting
      if (didUserUpvote) {
        console.log('here');
        incrementUserUpvotes(answer.uidCreated);
        incrementAnswerUpvotes(answer.answerID);
        appendToArrInDoc('answers', answer.answerID, 'upvotedBy', user.uid);
        console.log('done');
      }
    },
    [didUserUpvote, answer.uidCreated, answer.answerID, user.uid]
  );

推荐答案

每次使用重新加载页面时都会运行useEffect,因为变量是在初始呈现时初始化的,这会导致触发useEffect.

解决此问题的最好方法是使用useRef布尔值(为真时为init).如果为True,则将useRef设置为False.如果为False,则运行您在useEffect中拥有的代码.

以下是我将如何修改您的代码:


const init = useRef(true)
  useEffect(
    function () {
if(init.current){
init.current= false
}else{
      console.log('This prints on page load every time');
      // Check if the user is upvoting
      if (didUserUpvote) {
        console.log('here');
        incrementUserUpvotes(answer.uidCreated);
        incrementAnswerUpvotes(answer.answerID);
        appendToArrInDoc('answers', answer.answerID, 'upvotedBy', user.uid);
        console.log('done');
      }
}
    },
    [didUserUpvote, answer.uidCreated, answer.answerID, user.uid]
  );```

Reactjs相关问答推荐

如何使用React Router创建响应式主详细信息应用程序?

Reaction-路由v6动态路径RegExp

如何使用皮金贴图在Reactjs中制作 map 上的点之间的线的动画?

在Reaction中的第一次装载时,Use Effect返回空数组

用于获取带有事件处理程序的API的动态路由

是否为Reaction中未使用的组件生成Tailwincss样式?

在任何渲染之前在ReactJs中获取数据

在reduce()方法上得到NaN

React 状态不更新

为什么我的 Next.js (React) 组件只有在页面中时才有效?

部署到github pages时请求路径错误

如何在 ChartJS 中操作 Y 轴

React:如何设置光标 Select

NextJS htaccess 设置

在 redux 中分派到另一个减少时状态值不会改变

如果查询不存在,如何返回所有产品?

找不到元素 - 这是参考问题吗?

服务器端分页未按预期工作

调用函数以获取数据并在数据到达时导航到链接

React Router 6,一次处理多个搜索参数