gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:30:44 25 4
gpt4 key购买 nike

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

“不变违规: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>
)

关于javascript - 我在react.js 中编写for 循环时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29148936/

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