Подтвердить что ты не робот

Jquery in React не определен

Привет, я просто хочу получить ajax-запрос, но проблема в том, что jquery не определен в React. Реактивная версия 14.0

Сообщение об ошибке

 Uncaught ReferenceError: $ is not defined

У меня есть два файла:

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

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>
        );
    }
}
4b9b3361

Ответ 1

Попробуйте добавить jQuery к вашему проекту, например

npm i jquery --save

или если вы используете беседку

bower i jquery --save

то

import $ from 'jquery'; 

Ответ 2

  Я просто хочу получить ajax-запрос, но проблема в том, что jQuery не определен в React.

Тогда не используйте это. Используйте Fetch и посмотрите, что Fetch polyfill в React не полностью работает в IE 11, чтобы увидеть пример альтернативных способов его запуска

Примерно так

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

Ответ 3

Просто примечание: если вы используете функции стрелок, вам не нужно const = эта часть. Это может выглядеть так:

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

Ответ 4

Не проще, чем делать так:

1- Установите jquery в свой проект:

yarn add jquery

2- Импортируйте jquery и начинайте играть с DOM:

import $ from 'jquery';

Ответ 5

Добавьте "ref" в тег h1:

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

и
const { source } = this.props; измените на const { source } = this.refs;