【问题标题】:can I do many functions in one Onclick我可以在一个 Onclick 中完成许多功能吗
【发布时间】:2020-12-24 04:31:45
【问题描述】:

我的组件没问题,直到我尝试通过 Onclick 执行某些功能,所以我得到了错误:重新渲染太多。 React 限制了渲染的数量以防止无限循环。 我在添加时遇到了这个问题

onClick={setProduct(e.product_id), () => { addProduct(e.product_id) }

我的完整组件是:

import React, { useState, useEffect } from 'react'
import axios from 'axios';


const Cola = () => {
    const [products, setProducts] = useState([])
    const [product_id, setProduct] = useState("")

    useEffect(() => {
        getProd();
    }, []);

    const getProd = () => {
        axios.get(`http://localhost:3000/customer/product/2`)
            .then((result) => {
                setProducts(result.data);
                return 
            })
    }
    const addProduct = () => {
        axios.post(`http://localhost:3000/customer/additem`, {product_id})
    }
    return (

        <div className="row bg-light">
            {products.map((e, i) => (
                <div class="card " style={{ width: "18rem", margin: "32px", marginLeft: "50px" }}>
                    <img src={`${e.img_url}`} class="card-img-top" alt="..." />
                    <div class="card-body bg-secondary" >
                        <h5 class="card-title " style={{ color: "white" }}>{e.name}</h5>
                        <h5 class="card-title " style={{ marginTop: "20px", color: "white" }}>{e.price} jd</h5>
                        <a href="#" class="btn btn-success" onClick={setProduct(e.product_id), () => { addProduct(e.product_id) }} >اضافة</a>

                    </div>
                </div>
            ))}

        </div>
    )
}

export default Cola

【问题讨论】:

    标签: reactjs react-hooks rendering


    【解决方案1】:

    您正在直接调用该函数。所以它会触发重新渲染。 为 onClick 处理程序分配一个函数,而不是调用它。

    onClick={() => setProduct(e.product_id), () => { addProduct(e.product_id) }
    

    【讨论】:

      【解决方案2】:

      不能直接调用setProduct。

      onClick={() => setProduct(e.product_id), () => { addProduct(e.product_id) }
      

      另一种方式,简单易读。

      const clickHandler = (e) => {
        setProduct(e.product_id);
        addProduct(e.product_id);
      }
      
      <a href="#" class="btn btn-success" onClick={clickHandler} >Something</a>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-10
        • 1970-01-01
        相关资源
        最近更新 更多