【问题标题】:load json with reactjs用 reactjs 加载 json
【发布时间】:2016-03-14 12:07:13
【问题描述】:

我会非常感激谁能帮我解决这个问题 我有这个:

 var Country = React.createClass({
        render:function(){
            return(
                <nav> 
                <h2>list of country:</h2>
                { this.props.country}
                </nav>
            )
        }
    }) 
    var Jugador =React.createClass({
          componentWillMount: function(){
                var pais;
                var self = this;
                $.getJSON("https://restcountries.eu/rest/v1/all", function(data){
                    for(pais in data)
                    {
                        console.log(pais, data[pais].name);

                        return(
                            <Country key={i} country={self.render(data[pais].name)}> </Country>
                        )
                    }
                })
          },
    })

它不起作用,并出现此错误 未捕获的不变违规:createClass(...):类规范必须实现 render 方法。

【问题讨论】:

  • Jugador 没有渲染方法。它是一个反应组件吗?

标签: javascript json reactjs


【解决方案1】:

您的Jugador 组件需要实现render 方法。

【讨论】:

    【解决方案2】:

    在 React 中每个组件都必须有 render 方法,你应该实现它。我已经重构了你的代码,现在看起来像这样

    var Country = React.createClass({
      render: function() {
        return <div> 
          { this.props.country }
        </div>
      }
    })
    
    var Countries = React.createClass({
      getInitialState: function () {
        return { countries: [] };
      },
    
      componentWillMount: function(){
        $.getJSON("https://restcountries.eu/rest/v1/all", function (data) {
          this.setState({ countries: data })
        }.bind(this))
      },
    
      render: function () {
        var countries = this.state.countries.map(function (el, i) {
          return <Country key={i} country={ el.name } />
        }, this);
    
        return <nav>
          <h2>list of country:</h2>
          <div>{ countries }</div>
        </nav>;
      }       
    })
    

    Example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-24
      • 1970-01-01
      • 2015-08-25
      • 2019-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多