【问题标题】:Looping through a JSON object's entries and through react state, getting 'state undefined'循环遍历 JSON 对象的条目并通过反应状态,获得“未定义状态”
【发布时间】:2016-09-28 17:55:44
【问题描述】:

如果我偏离目标,请原谅,但我正在尝试将组件的状态设置为 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>
    );

使用此代码,我目前得到:

未捕获的类型错误:无法读取未定义的属性“状态”

任何人都知道为什么这不起作用?

【问题讨论】:

    标签: javascript json reactjs get


    【解决方案1】:

    问题是,$.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 >
        );
      }
    })
    

    【讨论】:

    • 恐怕还是不行。我得到完全相同的错误。另外,我在同一个函数中设置了另一个状态,它工作得很好。只是 this.state.content 不起作用。
    • @theJuls 你试过_this 方法吗?
    • 我做了 :( 我实际上复制了你在那里所做的,但它没有用。我现在也在用不同的方式弄乱它,看看它是否有效,但仍然没有。跨度>
    • 哦,没关系。我实际上让它工作了,在这里和那里进行了一些更改:) 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2016-05-14
    • 2020-08-20
    • 2018-09-26
    相关资源
    最近更新 更多