【问题标题】:How to include useRouter in function from one place with NextJS?如何使用 NextJS 从一处将 useRouter 包含在函数中?
【发布时间】:2022-08-03 06:32:58
【问题描述】:

我在 NextJS 项目中有一个功能,可以收集用于 firebase 分析的事件。

import analytics from \'@utility/firebase\';

const handleLogEvents = (event) => {
  const currentDate = new Date();
  logEvent(analytics, event.event_name, {
    branch_slug: event.branch_slug,
    timestamp: currentDate,
    ...event.properties,
  });
};

例如,当单击一个类别时,我确保将事件发送到 firebase。

const handleCategoryClick = (id, title, branchSlug) => {
  const event = {
    event_name: \'category_click\',
    properties: {
      branch_slug: branchSlug,
      category_id: id,
      category_name: title,
    },
  };
  handleLogEvents(event);
};

const { query } = useRouter(); 
const { branch } = query; // I have to call events on every page I post.

return(
  <div onClick={() => handleCategoryClick(id, title, branch)}>Example Div</div>
)

我在多个函数中调用事件。(产品、类别等)我在项目中使用的路线是动态的。每次向 Firebase 发送事件时,我都需要获取路由名称。每次调用 handleLogEvents 时,我都必须在页面上编写以下代码:

const { query } = useRouter();
const { branch } = query;

我是否有机会在函数中使用 handleLogEvents 而不是每次调用这个 useRouter 时都调用它?每次使用这个功能,似乎都没有必要去调用路由器。

    标签: reactjs next.js firebase-analytics next-router


    【解决方案1】:

    您可以将handleLogEvents 移动到一个可重复使用的自定义挂钩,您可以在其中包含useRouter 值。

    import { useCallback } from 'react'
    import { useRouter } from 'next/router'
    import analytics from '@utility/firebase';
    
    const useLogEvents = () => {
        const { query } = useRouter();
        const { branch } = query;
    
        const handleLogEvents = useCallback((event) => {
            currentDate = new Date();
            logEvent(analytics, event.event_name, {
                branch_slug: branch,
                timestamp: currentDate,
                ...event.properties
            });
        }, [branch]);
    
        return { handleLogEvents }
    };
    

    然后,您只需调用自定义挂钩即可从路由器中检索具有正确branch 值的handleLogEvents 函数。

    const { handleLogEvents } = useLogEvents();
    
    const handleCategoryClick = (id, title) => {
        const event = {
            event_name: 'category_click',
            properties: {
                category_id: id,
                category_name: title
            }
        };
        handleLogEvents(event);
    };
    

    【讨论】:

      猜你喜欢
      • 2021-05-29
      • 2020-09-20
      • 2023-03-26
      • 2021-06-19
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 2021-03-26
      相关资源
      最近更新 更多