reactjs - 将 Snipcart 添加到 Gatsby
问题描述
我正在尝试将 Snipcart 集成到 Gatsby (v2) 中。
我像这样编辑html.js
文件:
import React from "react"
import PropTypes from "prop-types"
export default class HTML extends React.Component {
render() {
return (
<html {...this.props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
{this.props.headComponents}
{/* Snipcart */}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://cdn.snipcart.com/scripts/2.0/snipcart.js" id="snipcart" data-api-key="UF45pIjZjAtZWJkYS00MGEwLWIxZWEtNjljZThjNTRiNjA4NjM2NDg1MzAzMzQyNfDrr48"></script>
<link href="https://cdn.snipcart.com/themes/2.0/base/snipcart.min.css" type="text/css" rel="stylesheet" />
</head>
<body {...this.props.bodyAttributes}>
{this.props.preBodyComponents}
<div
key={`body`}
id="___gatsby"
dangerouslySetInnerHTML={{ __html: this.props.body }}
/>
{this.props.postBodyComponents}
</body>
</html>
)
}
}
HTML.propTypes = {
htmlAttributes: PropTypes.object,
headComponents: PropTypes.array,
bodyAttributes: PropTypes.object,
preBodyComponents: PropTypes.array,
body: PropTypes.string,
postBodyComponents: PropTypes.array,
}
什么有效:
如果我创建一个 div:
<a href="#" class="snipcart-edit-profile">
Edit profile
</a>
Snipcart 工作并在单击时打开用户配置文件。
什么不起作用:
当我想使用公共 API 时,例如,如果我调用:
Snipcart.api.user.logout()
在一个函数中。
=> error 'Snipcart' is not defined no-undef
如何在我的所有应用程序中拥有全局 Snipcart 对象?
解决方案
no-undef
是一个 linter 错误,而不是运行时错误。因此,它并不表示您的代码运行时 Snipcart 不可用。
如果它不可用,您将在浏览器的控制台中收到此错误:ReferenceError: Snipcart is not defined
。
如果你正在使用eslint
,你可以在你的 eslint 配置中添加一个像这样的全局变量:
{
"globals": {
"Snipcart": false
}
}
或者,您可以在使用 Snipcart API 的文件中添加注释:/* global Snipcart:false */
该Snipcart
对象仅在浏览器中可用,因此您应确保在 Gatsby 预渲染您的网站时不要调用这些函数。这意味着您应该只调用Gatsby 的浏览器 API而不是 SSR 或 Node API的Snipcart.api.*
函数。
此外,为了确保您仅在脚本完全加载后才调用 Snipcart 的 API,您可以检查snipcart.ready
事件:
document.addEventListener('snipcart.ready', function() {
// any Snipcart.api.* call
});
推荐阅读
- postgresql - 是否可以通过函数 POSTGRESQL 中的变量更改运算符 =?
- c - GCC LD NOLOAD 链接器部分生成可加载段
- scala - 如何解决在 Windows10 的 scala 项目中编译 protobuf 的问题?
- sql - 查找子表列的 SUM 小于父子总列
- python - Django ListView在同一页面中的多个分页
- google-app-engine - 具有入口控制的 GAE,仅限内部
- angular - NWL NX Angular Jest 测试报告“无法找到描述”错误
- c# - ASP.NET Core api 项目 3.1 在 IIS 上发布
- python-3.x - Tkinter 列表框不会返回选定的元素
- safari - 为什么 Command-N 不能在 Safari 中打开新窗口?它会打开一个新选项卡