【问题标题】:Function runs forever in React Component函数在 React 组件中永远运行
【发布时间】:2020-04-01 23:27:32
【问题描述】:

我正在尝试使用一个函数将商品从详细信息页面添加到购物车到主 App 组件中的购物车数组。每当加载 Product Detail 组件时,该函数都会运行一次,当我单击“添加到购物车”按钮时,该函数会持续运行,直到 React 停止状态更新。

这是我的 App.js

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cart: []
    };
    this.handleAddToCart = this.handleAddToCart.bind(this);
  }

  handleAddToCart(product) {
    this.setState({
      cart: [this.state.cart, product]
    });
  }
  //I'm using React-Router with history.js
  render() {
    return (
      <Router history={history}>
        <Switch>
          <Route
            path="/product/detail"
            exact
            render={routeProps => (
              <ProductDetail {...routeProps} handleAddToCart={this.handleAddToCart} />
            )}
          />
        </Switch>
      </Router>
    );
  }
}

export default App;


这里是 ProductDetail.js

class ProductDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      product: {}
    };
  }

  componentDidMount() {
    // Getting data from React Router Link
    const product = this.props.location.state.product;
    this.setState({
      product: product
    });
  }

  render() {
    const product = this.state.product;
    return (
        <Link onClick={this.props.handleAddToCart(this.state.product)}>
          <Button>
             Add to Cart
          </Button>
        </Link>
    )
  }
}

基本上,我只希望在单击按钮时运行 handleAddToCart。另外,我将按钮的 onClick 设置为该功能,但它无法正常工作

【问题讨论】:

  • 可能不相关,但您应该在旧的购物车状态数组中传播:this.setState({ cart:[...this.state.cart, product] })

标签: javascript reactjs react-router


【解决方案1】:

您立即使用this.state.product 调用它,将其定义为匿名回调。您可以将onClick 处理程序添加到链接,但我认为您应该有一些关于缺少to 道具的错误/警告。

render() {
  const product = this.state.product
  return(
    <Link>
      <Button onClick={() => this.props.handleAddToCart(this.state.product)}>
         Add to Cart
      </Button>
    </Link>
  )
}

【讨论】:

  • @NicholasNorris 否定。 () =&gt; callback(...) !== callback(...)。前者等待被调用并调用回调,后者立即调用。
猜你喜欢
  • 2018-08-12
  • 1970-01-01
  • 2018-11-13
  • 2018-05-19
  • 1970-01-01
  • 1970-01-01
  • 2015-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多