简体   繁体   English

使用react.js的简单ajax请求

[英]simple ajax request with react.js

Im trying to display any data from an ajax request, done inside react.js. 我试图显示来自ajax请求的任何数据,在react.js中完成。 so far no joy.... 到目前为止没有快乐....

its trying to pull data from a test web API, JQuery is installed, although not necessary, i have looked at alternatives, but struggled so far to implement them. 它试图从测试Web API中提取数据,安装了JQuery,虽然没有必要,但我已经考虑了替代方案,但到目前为止还在努力实现它们。

For the request i am trying two things, to bind the data by this and with an append method from Jquery, both don't work. 对于请求我尝试两件事,通过这个和Jquery的append方法绑定数据,两者都不起作用。 Everything else renders and the console is not spitting out any errors. 其他所有内容都会渲染,控制台也不会出现任何错误。

I am trying to work towards a generic function that can easily be ported over for react-native, but im stuck even at this JQuery implementation. 我正在努力寻找一个可以轻松移植到本机反应的泛型函数,但即使在这个JQuery实现中也是如此。

var url = 'https://demo2697834.mockable.io/movies';

//main logic
var GetStuff= React.createClass({

    getInitialState: function() {
      return {
        entries: []
      };
    },

    componentDidMount: function() {
        $.ajax({
          url: 'https://demo2697834.mockable.io/movies',
          dataType: 'json',
          cache: false,
          success: function(data) {
            this.setState({entries: data});
            $('.test').append(data);
          }.bind(this),
          error: function(xhr, status, err) {
            console.error(this.props.url, status, err.toString());
          }.bind(this)
        });
      },

    render: function() {
      return (
        <div>{this.state.entries}</div>
      );
    }
});

//markup
<body style={MainStyles.alldivs}>
    <Header />
    <GetStuff/>
    <div class='test'></div>
    {this.props.children}
    <Footer />
</body>

Update 1 更新1

so i changed the properties to fit the entries declaration. 所以我改变了属性以适应条目声明。 No change, and i tried to pass in the props URL parameter, but no change either. 没有变化,我试图传递道具URL参数,但也没有变化。 I have also removed the old school JQuery append, im 100% trying to get on board with react, shame its not an easy segway transition. 我还删除了旧学校JQuery追加,我100%试图加入反应,羞辱它不是一个简单的赛格威过渡。

Do i need to change anything in the server config? 我是否需要更改服务器配置中的任何内容? i am using express? 我用快递?

Update 2 更新2

It' seems the componentDidMount function is not calling at all, to save confusion i will post my full code. 似乎componentDidMount函数根本没有调用,为了节省混淆,我将发布我的完整代码。

import React from 'react';
import ReactDom from 'react-dom';
import $ from "min-jquery";
import Header from './header';
import Footer from './footer';
//AJAX request
var GetStuff= React.createClass({
    getInitialState: function() {
      return {
        entries: []
      };
    },
    componentDidMount: function() {
        $.ajax({
          url: 'https://demo2697834.mockable.io/movies',
          dataType: 'json',
          cache: false,
          success: function(data) {
            this.setState({entries: data});
            console.log('success');
          }.bind(this),
          error: function(xhr, status, err) {
            console.error(this.props.url, status, err.toString());
            console.log('fail');
          }.bind(this)
        });
      },
    render: function() {
      return (
        <div> HERE: 
          {this.state.entries}
        </div>
      );
    }
});


// Stylesheet stuff is here, not important for this post.

//Render
var MasterLayout = React.createClass({ 
    render: function(){
        return(
            <html lang="en">
            <head>
                <title>{this.props.name}</title>
            </head>
            <body style={MainStyles.alldivs}>
                <Header />
                <GetStuff />
                {this.props.children}
                <Footer />
            </body>
            </html>
        )   
    }
});


// no idea if this is the correct setup, again docs are lacking on the real use of this.

    if(typeof window !== 'undefined') {
        ReactDom.reder(<MasterLayout />, document.getElementByID("content"));
    }
    module.exports = MasterLayout;

Well from what I can see is that you're not loading any URL , take this: 从我可以看到的是你没有加载任何URL ,采取这个:

url: this.props.url,

You've not assigned any props called url . 你没有分配任何名为url道具。 You've only assigned a variable named url at the top of your file. 您只在文件顶部指定了名为url的变量。

So what you can do is add something along the lines of this: 所以你可以做的是添加以下内容:

<GetStuff url="https://demo2697834.mockable.io/movies" />

Also I noticed you want to port this function over to react-native . 另外我注意到你想把这个函数移植到react-native I wouldn't use ajax for that. 我不会使用ajax Look into the fetch method...It's much the same as ajax and it's what react native uses by default. 查看fetch方法...它与ajax非常相似,它是默认情况下对本机使用的反应。 https://facebook.github.io/react-native/docs/network.html https://facebook.github.io/react-native/docs/network.html

Your request would look something like this: 您的请求看起来像这样:

fetch(this.props.url, {
  method: 'GET',
  headers: {
    'Accept': 'application/json',
  },
}).then (function (response) {return response.json()})
  .then(function (json) {/* Here is your json */})
  .catch(function (error) {/*Handle error*/});

Edit: 编辑:

Hmmm...it seems like you aren't able to access the props. 嗯......好像你无法访问道具。 Try console.log this.props inside your componentWillMount . componentWillMount尝试console.log this.props。 But I think I know the reasoning behind this.props.url not working inside your ajax function. 但我想我知道this.props.url背后的this.props.url在你的ajax函数中没有工作。

this. inside the ajax function refers to the ajax this, and not the react this.

What you could do is bind this to your ajax function or assign this.props.url to a variable outside the ajax function (this is what I would do). 你可以做的是将它绑定到你的ajax函数或将this.props.url给ajax函数之外的变量(这就是我要做的)。 Examples: 例子:

componentDidMount: function() {
        var url = this.props.url;
        $.ajax({
            url: url,

BTW, checkout this question for more details: React tutorial- why binding this in ajax call 顺便说一句,请查看此问题以获取更多详细信息: React tutorial-为什么在ajax调用中绑定它

Edit 2: 编辑2:

I noticed you're using plain react with no typescript or architecture such as redux. 我注意到你正在使用简单的反应,没有打字稿或体系结构,如redux。 I suggest you look into using babel with es6 and redux (it handles everything to do with the apps state, it's a must! It's a flux implementation). 我建议你考虑使用babel with es6redux babel with es6 (它处理与应用程序状态有关的一切,这是必须的!它是一个通量实现)。

I haven't used plain react in a while and you might have to set propTypes and then assign the props in your getInitialState function. 我暂时没有使用简单的反应,你可能必须设置propTypes然后在你的getInitialState函数中分配道具。

propTypes: {
    url: React.PropTypes.string,
},
getInitialState: function() {
    return {
        url: this.props.url,
    };
}

You can then go and access the url value using this.state.url . 然后,您可以使用this.state.url访问url值。

This is my working sample code. 这是我的工作示例代码。 Please refer to the syntax correctly in .bind(this) which is incorrect in your code. 请在.bind(this)中正确引用语法,这在您的代码中是不正确的。

<div id="element"></div>
<script type="text/jsx">

 var JavaEEWSTest = React.createClass({
                getInitialState: function () {
                    return {text: ''};
                },
                componentDidMount: function(){
                    $.ajax({
                        url: "http://localhost:8080/RestWeb/rest/city"
                    }).then(function(data) {
                        console.log(data.City.city);
                        this.setState({text: data.City.city});
                    }.bind(this))
                },
                render: function() {
                    return <div>Response - {this.state.text}</div>;
                }
            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM