Javascript React 中的 Jquery 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33351288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:58:29  来源:igfitidea点击:

Jquery in React is not defined

javascriptjqueryajaxreactjs

提问by Machycek

Hi I just want to receive ajax request, but the problem is that jquery is not defined in React. React version is 14.0

嗨,我只想接收 ajax 请求,但问题是 React 中没有定义 jquery。反应版本是14.0

Error message

错误信息

 Uncaught ReferenceError: $ is not defined

I have two files:

我有两个文件

index.js

index.js

import React from 'react'; 
import { render } from 'react-dom';
import App from './containers/App';  

const root = document.getElementById('root');  

render( 
  <App source='https://api.github.com/users/octocat/gists' />, 
  root
);

app.js

app.js

import React, { Component } from 'react';

export default class App extends Component {

    componentDidMount() {
        const { source } = this.props;

        console.log($); // throws error
    }

    render() {
        return (
            <h1>Hey there.</h1>
        );
    }
}

回答by Alexander T.

Try add jQueryto your project, like

尝试添加jQuery到您的项目中,例如

npm i jquery --save

or if you use bower

或者如果你使用凉亭

bower i jquery --save

then

然后

import $ from 'jquery'; 

回答by mplungjan

I just want to receive ajax request, but the problem is that jQuery is not defined in React.

我只是想接收ajax请求,但问题是在React中没有定义jQuery。

Then don't use it. Use Fetchand have a look at Fetch polyfill in React not completely working in IE 11to see example of alternative ways to get it running

那就别用了。使用Fetch并查看React中的Fetch polyfill 未完全在 IE 11 中工作,以查看使其运行的替代方法示例

Something like this

像这样的东西

const that = this; 
fetch('http://jsonplaceholder.typicode.com/posts') 
  .then(function(response) { return response.json(); }) 
  .then(function(myJson) { 
     that.setState({data: myJson}); // for example
  });

回答by Zach Robichaud

Just a note: if you use arrow functions you don't need the const that = this part. It might look like this:

请注意:如果您使用箭头函数,则不需要 const that = this 部分。它可能看起来像这样:

fetch('http://jsonplaceholder.typicode.com/posts') 
  .then((response) => { return response.json(); }) 
  .then((myJson) => { 
     this.setState({data: myJson}); // for example
});

回答by MUSTAPHA GHLISSI

Isn't easier than doing like :

并不比这样做更容易:

1- Install jquery in your project:

1- 在您的项目中安装 jquery:

yarn add jquery

2- Import jquery and start playing with DOM:

2- 导入 jquery 并开始玩 DOM:

import $ from 'jquery';

回答by Edhar Dowbak

Add "ref" to h1 tag :

将“ref”添加到 h1 标签:

<h1 ref="source">Hey there.</h1>

and
const { source } = this.props;change to const { source } = this.refs;


const { source } = this.props;更改为const { source } = this.refs;