gpt4 book ai didi

javascript - TypeError : this. $.ajax 请求状态为 null

转载 作者:行者123 更新时间:2023-12-03 05:56:36 25 4
gpt4 key购买 nike

var Movie = React.createClass({
getInitialState: function() {
$.ajax({
url: "getjsonarray.php",
dataType: 'json',
method: "POST",
data: {
startpoint: 0,
perpage: 2
},
success: function(data) {
this.setState({
json: data
}, function() {
}.bind(this));
}.bind(this),
});
return null;
},
render: function() {
return (
<div>
{
this.state.json.map(function(object, i){
return (
<div key={i}>
<h1>Movie {i}</h1>
<h2>Genre {i}</h2>
</div>
);
})
}
</div>
);
}
});
ReactDOM.render(<Movie/>, document.getElementById('container'));

这里我试图从后端获取json数组,通过react js迭代数组。但我只收到这个错误,

TypeError: this.state is null

有没有办法用ajax responcejson数组返回值?

这是我从后端得到的,

[{"id":"1","image":"http:\/\/images.prd.mris.com\/image\/V2\/1\/Yu59d899Ocpyr_RnF0-8qNJX1oYibjwp9TiLy-bZvU9vRJ2iC1zSQgFwW-fTCs6tVkKrj99s7FFm5Ygwl88xIA.jpg","price":"$1,975,000 ","address":"609 W Gravers Ln","area":"4,820 SqFt","beds":"5","baths":"5","desc":"Situated between fairmount park and the prestigious philadelphia cricket club, this beautiful 2+ acre property is truly","subdesc":"Courtesy of HS Fox & Roach-Chestnut Hill Evergreen"},{"id":"2","image":"http:\/\/images.prd.mris.com\/image\/V2\/1\/vGoNjc2jHGb87GlnnDQlf6LxeOUgIOn0bL6Wvn1nEnig2Ntq6W7xN5cOQBZZeNxl9O42DOkHUw0LNnj1ZB2KHA.jpg","price":"$1,500,000","address":"1220-32 N Howard St","area":"4,900 SqFt","beds":"1","baths":"1","desc":"A once in a lifetime opportunity to own a unique live \/ work space in one of philadelphia's most popular neighborhoods.","subdesc":"Courtesy of ll Banker Preferred-Philadelphia"}]

最佳答案

这里的问题是 ajax 是异步的,所以 getInitialState 首先进行,然后直接进行渲染,api 调用仍在传输中,并且在收到响应之前您实际上不会设置状态。我建议将 json 的初始状态设置为空数组,然后添加一个执行 ajax 请求并更新 json 状态的 componentDidMount 函数。

getInitialState: function() {  
return {
json: []
}
},

componentDidMount: function() {
$.ajax({
url: "getjsonarray.php",
dataType: 'json',
method: "POST",
data : {startpoint: 0, perpage: 2},
success: function(data) {
this.setState({json: data}, function(){

}.bind(this));

}.bind(this),
});
},

在我自己的应用程序中,每当我有一个依赖于 api 调用来获取其数据的组件时,我都会向我的组件添加一个加载状态,该状态最初为 true,然后在 true 时呈现不同的内容或某种形式的微调器。然后,一旦 api 调用完成,它将把加载状态设置为 false 并更新数据状态。

关于javascript - TypeError : this. $.ajax 请求状态为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39900488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com