我正在尝试在react.js中展示来自ajax请求的任何数据,但目前没有成功。
它正在尝试从测试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>
更新 1
我改变了属性以适应记录声明,但没有任何变化。我尝试传入 props URL 参数,但也没有变化。我还删除了老式的 JQuery append,我正在百分之百地尝试使用 React,可惜这不是一个容易的转型过渡。
我需要在服务器配置中更改任何内容吗?我正在使用 Express?
更新 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;
this.state.data
,但在getInitialState
中,您使用entries
而不是data
来启动状态。在成功回调中使用this.setState({entries: data});
并在渲染中调用this.state.entries
。 - Matthew Herbst$('.test').append(data);
这样的代码是没有用武之地的。你不应该手动更改DOM。移除test
div,只需使用GetStuff
中已有的渲染即可。 - Matthew Herbst