循环遍历JSON对象's条目并遍历react state,获取'state undefined'
Looping through a JSON object's entries and through react state, getting 'state undefined'
如果我偏离目标,请原谅,但我正试图将组件的状态设置为json对象,以便我可以用组件渲染它。
下面是我的组件中当前包含的内容:
render: function() {
this.serverRequest = $.get(this.props.source, function (data) {
this.state.content = $.parseJSON(data);
}.bind(this));
return (
<div>
{Object.keys(this.state.content).map(function (key) {
return <div>Key: {key}, Value: {this.state.content[key]}</div>;
})}
</div>
);
使用这个代码,我目前得到:
Uncaught TypeError: Cannot read property 'state' of undefined
有人知道为什么这不起作用吗?
问题是,$.get()
中的this
不在React的范围内。在渲染中调用setState()
会抛出一个错误。
var App = React.createClass({
getInitialState: function() {
return {
content: {},
}
},
componentDidMount: function() {
this.serverRequest()
},
serverRequest: function() {
var _this = this
$.get(this.props.source, function(data) {
_this.state.content = $.parseJSON(data);
})
},
render: function() {
return ( < div >
{
Object.keys(this.state.content).map(function(key) {
return <div > Key: {
key
}, Value: {
this.state.content[key]
} < /div>;
})
}
< /div >
);
}
})
相关文章:
- 循环遍历以数组为值的Javascript对象
- 遍历类元素数组,并在jquery中选择同级元素
- Jquery遍历表元素
- Chrome扩展:遍历不同的页面并收集数据
- 如何遍历包含对象的数组-javascript
- 遍历 JSON 对象并检查 URL 是否以某个值结尾
- 遍历AngularJs中的对象
- JQuery 遍历当前 SELECT 值
- 循环遍历包含另一个表单的表单
- 使用Yadda和Protractor重用步骤定义,遍历所需文件
- 遍历D3中所有数据点之间的所有值
- 自动遍历所有链接的事件
- JS.循环遍历多维数组,以计数元素在每列中的出现次数
- 如何使用 document.querySelectorAll 遍历选定的元素
- 使用Javascript反向遍历XML
- 当知道同一hiearch中至少有一个元素时,遍历到元素.结构使用jquery
- Netsuite Suitelet:在不达到治理限制的情况下,遍历事务行项目的列表加载和提交记录
- 遍历DOM查找字符串有时会正确返回
- 使用reactjs、localStorage和state(遍历)以模式显示表中的数据
- 循环遍历JSON对象's条目并遍历react state,获取'state undefined'