簡體   English   中英

為什么更改 state 時我的功能組件沒有重新渲染? (反應)

[英]Why my functional component doesn't re-render when change state? (react)

我被困在項目中,因為當我更新此 state 時,我的功能組件不會重新渲染。

const OneProduct = (props) => {
return (
<div className='productincart'>
    <div className='name'>{props.name}</div> 
    <div className='price'>Price: {props.price}</div>
    <div className='quantity'>{props.quantity}</div>
</div>)
}

const InsideCart = (props) => {
    const cartTemporary = props.sendCart
    const [cart, setCart] = useState([])

    useEffect(() => {
        setCart(cartTemporary)
        }, [cartTemporary])

    const showCart = () => {
        console.log(cart)
    }

    return (

        <div className='insidecart'>
            {cart.map(product => <OneProduct name={product.name} price= 
            {product.price} quantity={product.quantity} key={uniqid()} />)}
            <button onClick={showCart}>SHOW CART</button>
        </div>
    )
    }

在上面的代碼中,我將產品從商店放入cart ,接下來我想將其顯示在屏幕上。 當我將新商品放入cart車時( cart數組中的新 object),一切正常。 當我只更新購物車數組中已經存在的 object 數量時,什么也沒有發生。 數量更新后, cart會更新為新值,但不會導致組件重新渲染。

那就是要解決的問題,如何在數量值更新后使組件重新渲染。

在我添加到cart的對象格式下方,還添加了添加和增加數量的機制。

const Products = (props) => {
    const initialProducts = [
        { id: 0, name: "Fish - Betta splendens - Plakat Koi - Siamese fighting fish", image: image0, price: 23.17, quantity: 1 },
        { id: 1, name: "Fish - Betta splendens - Plakat - Siamese fighting fish", image: image1, price: 10.12, quantity: 1 },
        { id: 2, name: "Fish - Phenacogrammus interruptus - Congo tetra", image: image2, price: 5.19, quantity: 1 },
        { id: 3, name: "Fish - Thayeria boehlkei - Pinguin tetra", image: image3, price: 1.31, quantity: 1 },
        { id: 4, name: "Fish - Pterophyllum scalare - Angelfish", image: image4, price: 5.77, quantity: 1 },
        { id: 5, name: "Fish - Boeseman's rainbowfish Melanotaenia - Boesemani", image: image5, price: 4.90, quantity: 1 },
        { id: 6, name: "Fish - Ram cichlid - Mikrogeophagus ramirezi", image: image6, price: 4.61, quantity: 1 },
        { id: 7, name: "Fish - Corydoras aeneus sp.black venezuela", image: image7, price: 2.87, quantity: 1 },

    ]
    const [products, setProducts] = useState(initialProducts)
    const [toCart, setToCart] = useState([])

    const getProductId = (e) => {
        const idString = e.target.dataset.id
        const id = Number(idString)
        return id
    }

    const getProductById = (e) => {
        const id = getProductId(e)
        const itemFound = products.find(product => product.id === id)
        const foundedOrNot = toCart.find(product => product === itemFound)
        if (foundedOrNot === undefined) {
            setToCart([...toCart, itemFound])
        }
        else {
            const index = toCart.findIndex(product => product === itemFound)
            toCart[index].quantity = toCart[index].quantity + 1
        }

    }

    return (
        <div className="products">
            <Nav sendToCart={toCart} />
            <InsideCart sendCart={toCart} />
            <div className='container'>{products.map((product) => <Product onClick={getProductById} title={product.name} img={product.image} price={product.price} id={product.id} key={product.id} />)}</div>
        </div>
    );
};

還添加簡單的組件來確定渲染購物車內的內容。

const OneProduct = (props) => {
    return (<div className='productincart'><div className='name'>{props.name}</div> <div className='price'>Price: {props.price}</div><div className='quantity'>{props.quantity}</div></div>)
}

您的事件捕獲機制未正確實現。

對於解決方案,您應該將其替換為以下內容:

   <button onClick={() => showCart()}>SHOW CART</button>

您應該檢查此鏈接以了解解決方案的原因:

事件處理文檔

不久,文章包括以下內容:

這種語法的問題是每次 LoggingButton 呈現時都會創建不同的回調。 在大多數情況下,這很好。 但是,如果此回調作為道具傳遞給較低的組件,則這些組件可能會進行額外的重新渲染。 我們通常建議在構造函數中綁定或使用 class 字段語法,以避免此類性能問題。

我已經解決了這個問題。 問題未在product組件中使用setToCart 謝謝大家的建議!

更新代碼如下:

  const getProductById = (e) => {
        const id = getProductId(e)
        const itemFound = products.find(product => product.id === id)
        const foundedOrNot = toCart.some(product => product === itemFound)
        if (foundedOrNot === false) {
            setToCart([...toCart, itemFound])
        }
        else {
            const index = toCart.findIndex(product => product === itemFound)
            const newCart = toCart.map(cart => {
                if (cart.id === index) {
                    cart.quantity = cart.quantity + 1
                    return cart
                }
                return cart
            })
            setToCart(newCart)
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM