gpt4 book ai didi

javascript - 循环遍历 JSON 对象的条目和 react 状态,得到 'state undefined'

转载 作者:行者123 更新时间:2023-12-03 06:00:51 28 4
gpt4 key购买 nike

如果我偏离目标,请原谅,但我正在尝试将组件的状态设置为 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 - 循环遍历 JSON 对象的条目和 react 状态,得到 'state undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39754509/

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