一、简介
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.js
和 gatsby-browser.js
这两个文件中都提供了这两个API:wrapPageElement
和 wrapRootElement
。所以要保持两个文件中这两个API的代码一致性。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。