首页 > 解决方案 > 没有未使用的表达式问题 React

问题描述

我正在使用 React 制作电子商务网站。有一个ProductList.js列出的代码Product.js。我正在使用从context.js. 的代码是context.js-

    state = {
    products: [],
    detailProduct,
   };
   getItem = (id) => {
     let product = this.state.products.find((item) => item.id === id);
     return product;
   };
    
   handleDetail = (id) => {
     let product = this.getItem(id);
     this.setState(() => {
       return { detailProduct: product };
     });
   };
    
   addToCart = (id) => {
     console.log(`Hello from Add to Cart. Id is: ${id}`);
   };
   render() {
     return (
      <ProductContext.Provider
         value={{
           ...this.state,
           handleDetail: this.handleDetail,
           addToCart: this.addToCart
         }}
      >
        {this.props.children}
      </ProductContext.Provider>
     );
   }

这肯定不是完整的代码。如果您需要完整的代码,我也可以提供。

Product.jsis-的代码

<ProductConsumer>
        {(value) => {
          <div className="p-5 img-container" onClick={() => value.handleDetail(id)}>
            <Link to="/details">
              <img src={img} className="card-img-top" alt="Product Image" />
            </Link>
            <button className={inCart ? "in-cart cart-btn" : "cart-btn"} disabled={inCart ? true : false} onClick={() => value.addToCart(id)}>
              {inCart ? (
                <p className="text-capitalize mb-0" disabled>
                  Already in cart
                </p>
              ) : (
                <i className="fas fa-cart-plus"></i>
              )}
            </button>
          </div>
        }}
      </ProductConsumer>

我得到的错误 -

./src/components/Product.jsx
  Line 13:15:  Expected an assignment or function call and instead saw an expression  no-unused-expressions

Search for the keywords to learn more about each error.

请帮我解决这个问题...

标签: reactjsnpmreact-reduxnpm-startreact-context

解决方案


{您在消费者块中使用花括号。将这些更改为括号,如下所示:

<ProductConsumer>
        {(value) => (
          <div className="p-5 img-container" onClick={() => value.handleDetail(id)}>
            <Link to="/details">
              <img src={img} className="card-img-top" alt="Product Image" />
            </Link>
            <button className={inCart ? "in-cart cart-btn" : "cart-btn"} disabled={inCart ? true : false} onClick={() => value.addToCart(id)}>
              {inCart ? (
                <p className="text-capitalize mb-0" disabled>
                  Already in cart
                </p>
              ) : (
                <i className="fas fa-cart-plus"></i>
              )}
            </button>
          </div>
        )}
      </ProductConsumer>

阅读此答案以获得解释:https ://stackoverflow.com/a/35440330/1790728


推荐阅读