Javascript 未捕获类型错误:无法读取属性';然后';在React ajax调用中未定义的?
我是react js新手。我对在react js中加载初始数据有点困惑。 我很确定我的ajax调用可以正常工作,但我不知道如何处理这些数据并将json数据操作到我的组件中。 App.jsJavascript 未捕获类型错误:无法读取属性';然后';在React ajax调用中未定义的?,javascript,jquery,ajax,reactjs,flux,Javascript,Jquery,Ajax,Reactjs,Flux,我是react js新手。我对在react js中加载初始数据有点困惑。 我很确定我的ajax调用可以正常工作,但我不知道如何处理这些数据并将json数据操作到我的组件中。 App.js 如果定义了jQuery,请尝试在$.ajax()之前包含语句,以从getprofile()调用返回jQuery承诺对象 getprofile:function () { console.log('Gettinf data'); var url = 'http://localhost:3
如果定义了jQuery,请尝试在
$.ajax()
之前包含语句,以从getprofile()
调用返回jQuery承诺对象
getprofile:function () {
console.log('Gettinf data');
var url = 'http://localhost:3000/api/index';
// add `return` before `$.ajax()` to return jQuery promise
// from `getprofile()` call
return $.ajax({
url:url,
dataType:'json',
cache:false,
success:function success(data) {
console.log(data);
}.bind(this),
error:function error(xhr,status,err) {
console.log(err);
}
})
}
对于我来说,在react中使用AJAX似乎很奇怪,因为有react本机获取方法来实现这一点 我会这样做的
getProfile: function() {
fetch('http://localhost:3000/api/index',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
});
然后在App.js中
这就是您的错误所在-您需要在.then中返回响应
componentDidMount: function(){
api.getprofile().then(response => response.json())
.then( (json => {
this.setState({
data: json
});
});
}
jQuery是在哪里定义的?jQuery是在index.html文件中定义的,Ajax正在工作,但我不知道如何处理该数据。
$。Ajax()
不是从getprofile()
调用返回的?@charlietfl是的,先生,那是我的错误。$.Ajax()正在返回json数据。是的!!数据正在获取,但现在发生了类型错误:This.setState不是一个函数,而不是使用.bind()
在成功
时,尝试使用$.ajaxSetup()
设置$.ajax()的上下文
调用对象,其中setState
是一个方法$.ajaxSetup({context:/*object to set this for$.ajax()*/})
,另外,尝试使用.then()
来处理响应,而不是成功
返回$.ajax({url:url,数据类型:'json',cache:false})
您尝试过在$.ajax()将设置为应用程序吗
在module.exports={getprofile:function(){}
中调用?实际上我忘了在componentdidmount中绑定数据
getProfile: function() {
fetch('http://localhost:3000/api/index',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
});
componentDidMount: function(){
api.getprofile().then(response => response.json())
.then( (json => {
this.setState({
data: json
});
});
}