使用 react.js 的简单 ajax 请求

Pad*_*ddy 7 ajax jquery reactjs

我试图显示来自 ajax 请求的任何数据,在 react.js 中完成。至今没有快乐....

它试图从测试 Web API 中提取数据,安装了 JQuery,虽然不是必需的,但我已经研究了替代方案,但到目前为止努力实现它们。

对于请求,我正在尝试两件事,通过 this 和来自 Jquery 的 append 方法绑定数据,两者都不起作用。其他一切都呈现出来,控制台没有吐出任何错误。

我正在努力开发一个可以轻松移植到 react-native 的通用函数,但我仍然坚持使用这个 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>
Run Code Online (Sandbox Code Playgroud)

更新 1

所以我更改了属性以适合条目声明。没有变化,我尝试传入 props URL 参数,但也没有变化。我还删除了旧的 JQuery 附加,我 100% 试图加入 React,可惜这不是一个简单的赛格威过渡。

我需要更改服务器配置中的任何内容吗?我用快递?

更新 2

似乎 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;
Run Code Online (Sandbox Code Playgroud)

Jam*_*111 4

从我看来,你没有加载任何内容URL,请执行以下操作:

url: this.props.url,
Run Code Online (Sandbox Code Playgroud)

您尚未分配任何名为 的道具url。您仅在文件顶部分配了一个名为 url 的变量。

所以你可以做的就是添加一些类似的内容:

<GetStuff url="https://demo2697834.mockable.io/movies" />
Run Code Online (Sandbox Code Playgroud)

我还注意到您想将此功能移植到react-native. 我不会用ajax这个。查看该方法...它与 React Native 默认使用的方法fetch非常相似。https://facebook.github.io/react-native/docs/network.htmlajax

您的请求将如下所示:

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*/});
Run Code Online (Sandbox Code Playgroud)

编辑:

嗯...看来您无法访问道具。尝试在您的componentWillMount. this.props.url但我想我知道不在你的函数内工作背后的原因ajax

this. inside the ajax function refers to the ajax this, and not the react this.
Run Code Online (Sandbox Code Playgroud)

您可以做的是将其绑定到您的 ajax 函数或分配this.props.url给 ajax 函数外部的变量(这就是我要做的)。例子:

componentDidMount: function() {
        var url = this.props.url;
        $.ajax({
            url: url,
Run Code Online (Sandbox Code Playgroud)

顺便说一句,请查看这个问题以获取更多详细信息:React教程-为什么在ajax调用中绑定它

编辑2:

我注意到你使用的是普通的 React,没有打字稿或 redux 等架构。我建议您考虑使用babel with es6and redux(它处理与应用程序状态有关的所有内容,这是必须的!它是一个 Flux 实现)。

我有一段时间没有使用普通的 React,你可能必须设置 propTypes,然后在 getInitialState 函数中分配 props。

propTypes: {
    url: React.PropTypes.string,
},
getInitialState: function() {
    return {
        url: this.props.url,
    };
}
Run Code Online (Sandbox Code Playgroud)

然后您可以使用 访问 url 值this.state.url