【问题标题】:Display array element ReactJS显示数组元素 ReactJS
【发布时间】:2016-11-17 13:19:24
【问题描述】:

UPD:如何在我的组件中显示数组元素 (WeatherCityName - h2)?可以看到加载了数组,但是当我点出属性时——出现错误,可能是语法有问题?

  var WeatherBox = React.createClass({
   handleWeatherSubmit: function(text) {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: 'cityName=' + text,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  getInitialState: function() {
    return {data: []};
  },
  render: function() {
    return (
      <div className="wetherBox">
      <h1> Weather</h1>
      <WeatherForm onWeatherSubmit={this.handleWeatherSubmit} />
      <WeatherCityName data={this.state.data[0]} />
      <WeatherList data={this.state.data} />
      </div>
      );
  }
});

var WeatherCityName = React.createClass({
    render: function(){
        return(
            <h2>{this.state.data[0].cityName}</h2>
            );
    }
});

【问题讨论】:

  • 你想用this.props(function(weatherItem) { ... });做什么?另外,将该 JSX 与 return 放在同一行。
  • 我只尝试返回一次

标签: javascript reactjs syntax


【解决方案1】:

当然,只需将&lt;h2&gt;{weatherItem.cityName}&lt;/h2&gt; 直接放在&lt;div&gt; 中即可。

var WeatherList = React.createClass({
  render: function() {
    var weatherNodes = this.props.data.map(function(weatherItem) {
      return (
        <div className="city-item-with-title">
          <h2>{weatherItem.cityName}</h2>
          <WeatherItem 
            cityid={weatherItem.cityid}
            type={weatherItem.type} 
            src={weatherItem.src} 
            temp={weatherItem.temp} 
            tempFrom={weatherItem.tempFrom} 
            tempTo={weatherItem.tempTo} 
            key={weatherItem.id}
          />
        </div>
      );
    });

    return (
      <div className="weatherList">
        {weatherNodes}
      </div>
    );
  }
});
  • 编辑:我不确定要使用哪个天气项目作为标题,也许是this.props.data[0]
  • 编辑 2:假设您想使用第一个天气项目。
  • 编辑 3:每个 weatherItem 一个标题,与对应的 weatherItem 一起分组在一个 div 中。

【讨论】:

  • 这个变种会导致错误:Uncaught ReferenceError: weatherItem is not defined.json 格式的数据:[{"id": 1, "cityName": "Kiev","typeid": 1, "type": "morning", "src": "www", "tempFrom":"+1", "tempTo": "+2"}, {"id": 1, "cityName": "Kiev","typeid": 1, "type": "morning", "src": "www", "tempFrom":"+1", "tempTo": "+2"},] 我需要向他们展示方法映射,但是"cityName" 我只需要在&lt;h2&gt; 中显示一次
  • 是的,我的回答有点不清楚。 &lt;h2&gt;{weatherItem.cityName}&lt;/h2&gt;weatherItem 内部没有定义。您想为标题使用哪个 weatherItem?
  • 我添加了所有代码。 weatherItem - 这是一个 json 格式的数组。我只需要在h2 中显示cityTitle (cityName = "Kiev") 一次,在方法@​​987654333@ 中显示其他数据
  • 好吧,总是基辅?然后只需&lt;h2&gt;Kiev&lt;/h2&gt;
  • 不,并非总是如此。 cityname 并通过 ajax 更改和加载数据
猜你喜欢
  • 2021-04-02
  • 1970-01-01
  • 2015-03-07
  • 1970-01-01
  • 2020-12-04
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
相关资源
最近更新 更多