关于reactjs:如何在Gatsby中修复乘法Snipcart自定义html?

How to fix multiplying Snipcart custom html in Gatsby?

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

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

Snipcart自定义html组件:

1
2
3
4
5
6
7
8
9
10
  // 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布局组件:

1
2
3
4
5
export default class Layout extends Component {
  render() {    
    return (
     
        <CustomSnipcartText /> ...

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


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

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

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

另外,可以使用Snipcart.subscribe代替Snipcart.execute :)


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

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

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

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