weixin_33725239 2016-03-09 11:10 采纳率: 0%
浏览 48

使用React进行Ajax调用

I come from the world where you did Ajax with jQuery. Now I'm trying a data-binding framework such as React.

I have a question for it anyhow. How do you make an Ajax call using React?

The examples I have found such as this or this seems to have used jQuery for making Ajax call since they are using $.get() and $.ajax()

However when I tried those snippet I get ReferenceError: $ is not defined. Do I need to reference jQuery to use Ajax in React?

Here's my code snippet

import React from 'react'
import ReactDOM from 'react-dom'

var MyApp = React.createClass({
    getInitialState: function() {
        console.log("getInitialState")
        return {
            username: 'stardustz'
        };
    },

    componentDidMount: function() {
        console.log("componentDidMount");
        $.ajax({
            url: this.props.source,
            dataType: 'json',
            success: function() {
                console.log("success");
            }.bind(this)
        });
        console.log(this.props.source);
        console.log(this.serverRequest);
    },
    componentWillUnmount: function() {
        console.log("componentWillUnmount");
    },

    render: function() {
        console.log("render");
        return (
            <div>
                Hello {this.state.username}.
            </div>
        );
    }
});

ReactDOM.render(
    <MyApp source="http://localhost:8080/api/person/getAll" />,
    document.getElementById('myapp')
);
  • 写回答

4条回答 默认 最新

  • weixin_33698043 2016-03-09 11:26
    关注

    React as a library provides no built in mechanism for AJAX. If you want to use jQuery inside your React components you'll need to include it via a script tag or import it as a node module. jQuery's ubiquity makes it a common choice for tutorials, but that's the only reason you're seeing it. You're free to use whatever AJAX library you'd like.

    评论

报告相同问题?