I'我在react.js中编写for循环时遇到问题

I'm having trouble writing a for loop in react.js

本文关键字:for 循环 问题 遇到 我在 js react      更新时间:2023-09-26

我是编程新手,正在学习Facebook的react.js。我发现一个网站有一个使用react构建"购物车"的教程。我试图使用for循环修改它以添加更多项目,但它一直给我"意外的令牌}"错误,然后是这个错误:

不变冲突:FluxProduct.render():必须返回有效的ReactComponent。您可能返回了未定义的、数组或其他无效对象。

我意识到有一个类似的问题得到了回答,但对我没有帮助

这个项目中有很多代码,但我遇到的问题是这样的:

render: function() {
    var rows = [];
    var ats = (this.props.selected.sku in this.props.cartitems) ?
      this.props.selected.inventory - this.props.cartitems[this.props.selected.sku].quantity :
      this.props.selected.inventory;
    for (var i=0; i<2; i++){<div className="flux-products">
        <img src={'img/' + this.props.product.image}/>
        <div className="flux-products-detail">
          <h1 className="name">{this.props.product.name}</h1>
          <p className="description">{this.props.product.description}</p>
          <p className="price">Price: ${this.props.selected.price}</p>
          <select onChange={this.selectVariant}>
            {this.props.product.variants.map(function(variant, index){
              return (
                <option key={index} value={index}>{variant.type}</option>
              )
            })}
          </select>
          <button type="button" onClick={this.addToCart} disabled={ats  > 0 ? '' : 'disabled'}>
            {ats > 0 ? 'Add To Cart' : 'Sold Out'}
          </button>
        </div>
      </div>}
    return ("flux-products-detail"
    );
  },
});

如果你想要/需要原始代码和项目的其余部分,我会非常乐意提供它。

看起来您正试图在for循环中组成三个组件。但是,for循环的结果没有存储到变量中,也没有在返回函数中正确呈现。

// Use a variable to store the result of the loop
return (
  <div>
    {myComponent}
  </div>
)

在使用循环为React元素生成内容的情况下,我通常将其公式化为:

render: function() {
var items = [];
for(var i = 0; i < this.state.listOfItems.length; i++) {
    items.push( <ItemComponent value={this.state.listOfItems[i].value} />
}
return ( <div> {items} </div>)
};

因此,您需要做的是从渲染返回一些JSX,以便对渲染作出反应。正如@FelixKling所说,JSX并不是魔术,你本质上只是返回了一堆React.createElement函数。