一、简介

Gatsby 在 gatsby-browser.js 文件中提供了一些API,可供开发者 监控浏览器的特定事件 和 写一些全局组件。


二、API 说明
1、onRouteUpdate
  • 功能:监控页面切换的事件

    // gatsby-browser.js
    const React = require("react")
    
    // Logs when the client route changes
    exports.onRouteUpdate = ({ location, prevLocation }) => {
      console.log("new pathname", location.pathname)
      console.log("old pathname", prevLocation ? prevLocation.pathname : null)
    }

2、wrapPageElement
  • 功能:用于plugin,给所有页面增加一层父容器

    // gatsby-browser.js
    const React = require("react")
    const Layout = require("./src/components/layout")
    
    // Wraps every page in a component
    exports.wrapPageElement = ({ element, props }) => {
      return <Layout {...props}>{element}</Layout>
    }

三、重要规则
1、一致性

gatsby-ssr.jsgatsby-browser.js 这两个文件中都提供了这两个API:wrapPageElementwrapRootElement 。所以要保持两个文件中这两个API的代码一致性。


四、参考文档

Learn_anything
7 声望0 粉丝

收集互联网优质资源!


引用和评论

0 条评论