【问题标题】:Where to put JQuery in React Component?将 JQuery 放在 React 组件中的什么位置?
【发布时间】:2019-08-26 17:19:04
【问题描述】:

我在我的 React 应用程序中使用物化 css 库。 所以,我想从中使用“模态”。有两种初始化方式:

document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.modal');
var instances = M.Modal.init(elems, options);
 });

// Or with jQuery

$(document).ready(function(){
$('.modal').modal();
});

所以,我通常会这样做:

componentDidMount() {
    const $ = window.$;
    $('.dropdown-trigger').dropdown();
    $(document).ready(function () {
        $('.modal').modal();
    })
}

这一切都对我有用,但现在我的 ComponentDidMount() 中有一个额外的方法,它请求服务器 api:

componentDidMount() {
    this.getCurrentUser();
    const $ = window.$;
    $('.dropdown-trigger').dropdown();
    $(document).ready(function () {
        $('.modal').modal();
    })
}

getCurrentUser() {
    fetch('api/user/'+ localStorage.getItem("currentUser") +'/me', {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    })
        .then(response => {
            if (!response.ok) {
                this.setState({
                    isLoadong: false,
                    failed: true
                })
            }
            else {
                response.json().then(user => {
                    this.setState({
                        user: user,
                        isLoadong: false,
                        failed: false
                    })
                });
            }
        })
}

那么为什么模态现在不起作用? 如何正确地做到这一点?

【问题讨论】:

  • 不要!使用反应材料库
  • 这是一个非常糟糕的实现。我建议研究您可以使用的反应库。网上有很多!

标签: javascript jquery reactjs material-design


【解决方案1】:

您只想在 React 应用程序树结构的叶节点中使用 jQuery。如果这个组件有任何子组件,这是一个坏主意。如果它是叶节点组件,那么您需要将 jQuery 逻辑放在 componentDidMount() 函数中。

这个页面有一些关于这个主题的有用材料:https://reactjs.org/docs/integrating-with-other-libraries.html

【讨论】:

  • 谢谢!你知道为什么当我将 this.getCurrentUser() 方法添加到 componentDidMount 时它停止工作吗?
  • 对不起,我没有。这看起来还不错。我会尝试在你之后添加一个捕获。类似 .then(// code).catch((err) => { console.log('error: ' + err); })
猜你喜欢
  • 1970-01-01
  • 2013-12-26
  • 2010-09-16
  • 1970-01-01
  • 2012-11-25
  • 2010-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多