1

我最近将一个站点迁移到 Gatsby[v2] 并发现事件发生后 Snipcart 的自定义 html 会成倍增加。如何防止 Snipcart 自定义 HTML 在每次页面导航或事件发生时成倍增加?当我打开模式时,多重渲染是可见的。我不确定这是 React 组件生命周期问题还是 Gatsby[v2] 布局组件问题。

CustomSnipcartText 组件使用 componentDidMount 调用 Snipcart api 并使用这些方法将文本绑定到 DOM。CustomSnipcartText 组件被导入到 Gatsby 布局组件中。我尝试将组件导入到打开模态函数的位置,结果没有变化。

Snipcart 自定义 html 组件:

  // Binds the Snipcart subscription services to the component
  componentDidMount() {
  /* global Snipcart:false */
    Snipcart.execute('bind', 'cart.opened', function() {
      Snipcart.execute('unbind', 'cart.opened')
      /* global $: false */
      let html = $('#cart-content-text').html()
      $(html).insertBefore($('#snipcart-footer'))
    })
  } ....

GatsbyJs 布局组件:

export default class Layout extends Component {
  render() {    
    return (
      <div className="wrapper">
        <CustomSnipcartText /> ...

我希望 CustomSnipcartComponent 在任何事件发生后都不应成倍增加。

4

2 回答 2

1

当您的代码运行时,它会附加一个新的片段,#cart-content-text但如果它不是第一次运行,它将继续附加更多。

Snipcart 代码不知道您注入的 HTML,因此您有责任将其删除或更新其内容。

您必须添加一些逻辑来检查您的自定义 HTML 是否已经存在。


此外,Snipcart.subscribe可以用来代替Snipcart.execute:)

于 2019-06-06T15:55:25.717 回答
0

根据Jean-Sébastien-Tremblay的帖子,我意识到问题出在 Gatsby Layout 组件中。

在版本 1 中,布局组件是一个特殊的组件,它充当页面组件之外的包装器。在版本 2 中,布局组件是一个常规组件,您可以将其包装在要使用的页面上。更多关于推理的信息可以在 Gatsby博客上找到。

该项目中的所有页面都是动态创建的。

我用gatsby-plugin-layout重新实现了 v1 的布局。我将 components 目录外的组件移回 layouts 目录,并将文件名Layout.jsindex.js.

于 2019-06-10T10:33:05.523 回答