React无法识别DOM元素上的`totalPrice and totalQuantity`属性,并且超过了最大更新深度错误

问题描述 投票:0回答:1

我写了一个代码来计算购物车的总数量和总价格。但是,向子组件发送引用存在一个问题。 (App.js-> Navigation.js-> CartProcess.js-> CartList.js,App.js-> CartList.js(用于路由))CartProcess的链接如下所示。这是下面显示的问题。

React无法识别DOM元素上的totalQuantity属性。如果您有意让它作为自定义属性出现在DOM中,请将其拼写为小写totalquantity。如果不小心从父组件传递了它,请将其从DOM元素中删除。

React无法识别DOM元素上的totalPrice属性。如果您有意让它作为自定义属性出现在DOM中,请将其拼写为小写totalprice。如果不小心从父组件传递了它,请将其从DOM元素中删除。

<DropdownItem>
   <Link to="/cart"
    totalQuantity={ this.props.totalQuantity}
    totalPrice={ this.props.totalPrice }
   >Cart Detail</Link>
</DropdownItem>

App.js还包括CartList组件以显示购物车详细信息。

渲染部分

    <Route exact path="/cart" render={
                  routeProps => (
                    <CartList
                      {...routeProps}
                      cart={this.state.cart}
                      removeFromCart={this.removeFromCart}
                      totalQuantity={this.totalQuantity}
                      totalPrice={this.totalPrice}
                    />
                  )
                } />

  }

当我像这样的顺序从父组件调用totalQuantity和totalPrice函数时。

App.js <- Navigation.js <- CartProcess.js

我显示以下错误。

错误:已超过最大更新深度。当组件重复调用componentWillUpdate或componentDidUpdate内部的setState时,可能会发生这种情况。 React限制了嵌套更新的数量,以防止无限循环。

CartList.js

renderTotalPriceAndTotalQuantity(){
        return (
            <div>
                <Alert color="primary">
                Total Price : { this.props.totalPrice() }
            </Alert>
            <Alert color="secondary">
                Total Quantity : { this.props.totalQuantity() }
            </Alert>
            </div>
        )
    }

App.js

totalQuantity = () => {
    console.log("totalQuantity");

    this.setState({
      totalQuantity: this.state.cart.reduce(
        (sum = 0, cartItem) => sum + cartItem.quantity,
        0
      )
    });

    console.log(this.state.totalQuantity);
  }

  totalPrice = () => {
    console.log("totalPrice");

    this.setState({
      totalPrice: this.state.cart.reduce(
        (sum = 0, cartItem) => sum + cartItem.quantity * cartItem.product.unitPrice,
        0
      )
    });

    console.log(this.state.totalPrice);
  }

我该如何解决问题?

谢谢。

reactjs
1个回答
0
投票

CartList.js中,您实际上是在html中调用导致此问题的函数。尝试这样做:

renderTotalPriceAndTotalQuantity(){
        return (
            <div>
                <Alert color="primary">
                Total Price : { this.props.totalPrice }
            </Alert>
            <Alert color="secondary">
                Total Quantity : { this.props.totalQuantity }
            </Alert>
            </div>
        )
    }
© www.soinside.com 2019 - 2024. All rights reserved.