简体   繁体   中英

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

I'm new to programming and I'm learning Facebook's react.js. I found a website that has a tutorial which builds a "shopping cart" using react. I tried to modify it to add more items using a for loop but it keeps giving me "unexpected token }" errors followed by this error:

"Invariant Violation: FluxProduct.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object."

I realize there is a similar question that was answered but it didn't help me.

There is quite a bit of code in this project but the particular spot I'm having trouble with looks like this:

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"

    );
  },

});

If you want/need the original code and the rest of the project I'd be more than happy to provide it.

It looks like you are trying to compose three components in the for loop. However the result of the for loop is not stored to a variable, and not rendered properly in the return function.

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

In the case of using a loop to generate content for a React element, I usually formulate it something like this:

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>)
};

So what you need to do is return from render some JSX for react to Render. as @FelixKling said, JSX isn't magic, you're essentially just returning a bunch of React.createElement functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM