在ReactJs中更新组件更新的jQuery光滑轮播 [英] Updating jQuery slick carousel on component update in ReactJs

查看:97
本文介绍了在ReactJs中更新组件更新的jQuery光滑轮播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用ReactJs,我可以说它非常棒。但我遇到了一个问题,我似乎无法弄清楚如何解决这个问题。

I just started with ReactJs and I can tell it's really awesome. But I came across an issue and I can't seem to figure out how to resolve this.

我正在尝试实现一个自动搜索过滤组件,根据名称过滤项目。在这里,我使用电影和电影标题作为例子。搜索有效,但是当我尝试添加一些jQuery时,我在尝试过滤搜索结果时遇到此错误:

I'm trying to implement an automatic search filtering component that filters items based on their name. Here, I'm using movies and movie titles as an example. The search works, but as soon as I try to add some jQuery to the mix, I get this bug while trying to filter my search results:

不变违规:ReactMount:两个有效但不相等的节点具有相同的 data-reactid

Invariant Violation: ReactMount: Two valid but unequal nodes with the same data-reactid

那些带有相同的 data-reactid 是jQuery插件创建的节点,即光滑的旋转木马。

Those nodes with the same data-reactid are the nodes created by the jQuery plugin, namely Slick carousel.

在这里你可以自己试试:

Here you can try it yourself:

Plunker

一旦发表评论第45行 script.jsx ,您可以看到我的搜索功能正常运行。

As soon as you comment line 45 of script.jsx, you can see my search feature is working.

问题是,jQuery插件加载在 componentDidMount 中,如 React docs ,但是当DOM发生变化时,一切都搞砸了,因为函数只调用一次。我需要在数据更新时重新加载jQuery插件,但我无法确切知道何时,何地以及如何。

The thing is, the jQuery plugin is loaded in componentDidMount, as suggested in the React docs, but when the DOM gets changed, everything is messed up, because the function is only called once. I need to reload the jQuery plugin when the data gets updated but I can't figure out exactly when, where and how.

我尝试使用 componentDidUpdate 相反,但它没有按预期工作。它也不会在页面加载时被调用。

I tried using componentDidUpdate instead, but it didn't work as expected. And it wouldn't get called on page load neither.

非常感谢!

推荐答案

最简单的解决方案可能是这样做:

The simplest solution may be to do this:

componentDidMount: function(){
  $(this.getDOMNode()).slick();
},
componentWillUpdate: function(){
  $(this.getDOMNode()).slick('unslick'); //remove the added dom elements
},
componentDidUpdate: function(){
  $(this.getDOMNode()).slick();
},
componentWillUnmount: function(){
  $(this.getDOMNode()).slick('unslick');
},

因为即使反应没有引发错误,这也是最简单的添加/删除元素到光滑轮播的方法。这是多么可行取决于你计划渲染的元素数量以及高效的滑动旋转木马。

since even if react didn't throw an error this would be the easiest way to add/remove the elements to slick carousel. How feasible this is will depend on how many elements you plan on rendering and how performant slick carousel is.

这篇关于在ReactJs中更新组件更新的jQuery光滑轮播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆