如何解决Gatsby中Snipcart自定义html的乘法问题?

时间:2019-05-30 11:44:35

标签: reactjs gatsby snipcart

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

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

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不会在发生任何事件后相乘。

2 个答案:

答案 0 :(得分:1)

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

Snipcart代码无法识别您注入的HTML,因此您有责任将其删除或更新其内容。

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


也可以使用Snipcart.subscribe代替Snipcart.execute:)

答案 1 :(得分:0)

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

在版本1中,布局组件是一个特殊的组件,充当页面组件外部的包装器。 在版本2中,layout组件是常规组件,您可以将其包装在要使用它的页面上。可以在盖茨比blog上找到有关推理的更多信息。

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

我使用gatsby-plugin-layout从v1重新实现了布局。我将组件从组件目录外移回了布局目录,并将文件名从Layout.js更改为index.js