首页 > 解决方案 > React/Redux 组件中导致重定向的奇怪错误?

问题描述

在主屏幕上,当您单击产品列表时,它会进入包含 1 个产品及其详细信息的产品屏幕页面。当我将 onClick 处理程序和 onChange 处理程序添加到 productScreen.js 中的按钮和 qty select 时,它会导致它每次进入 productScreen (/products/:id) 时都会自动重定向到 /cart。

productScreen.js

import Rating from '../components/Rating'
import { useParams, Link } from 'react-router-dom'
import { useSelector, useDispatch} from 'react-redux'
import { useEffect, useState } from 'react'
import { productDetailCreator } from '../state/actions/productActions'
import { addCartAction } from '../state/actions/cartActions'


const ProductScreen = (props) => {
    const { id } = useParams()
    const dispatch = useDispatch()
    const { loading, error, product } = useSelector(state => state.productDetail)

    // Load Product
    useEffect(() => {
        dispatch(productDetailCreator(id))
    }, [dispatch, id])

    const [qty, setQty] = useState(0)

    // Add to Cart Function
    const addToCartHandler = (id, qty) => {
        dispatch(addCartAction(id, qty))
        props.history.push('/cart')
    }

    return (
        <div className="max-w-5xl mx-auto my-36">
            <div className=" mt-8 p-2">
                <Link to="/" className="flex items-center text-gray-400 font-light">
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-3 w-3 mr-1 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M11 19l-7-7 7-7m8 14l-7-7 7-7" />
                    </svg>
                    Back
                </Link>
            </div>
            { loading? (
                <h3>Loading...</h3>
            ) : error ? (
                <h3>{error}</h3>
            ) : (
                <div className="flex flex-col sm:flex-row items-center my-7 px-8 py-2">
                    <div className="p-5 sm:w-2/5">
                        <img className="" src={product.image} alt={product.name} />
                    </div>
                    <div className="flex flex-col sm:w-2/5 p-5">
                        <span>{product.name}</span>
                        <hr className="my-4"/>
                        <Rating product={product} />
                        <hr className="my-4"/>
                        <span>Price: ${product.price}</span>
                        <hr className="my-4"/>
                        <span>Description: {product.description}</span>
                    </div>
                    <div className="flex flex-col sm:w-1/5 p-5">
                        <span className="text-center">Price: ${product.price}</span>
                        <span className="text-center mt-1">Status: {product.countInStock > 0 ? 'In Stock' : 'Out of Stock'}</span>
                        <div className="px-4 qty-select">
                                        <label htmlFor="qty">Qty</label>
                                        <select onChange={(e) => setQty(e.target.value)} name="qty" value="1" >
                                            { [...Array(10).keys()].map(x => (
                                                <option value={x+1} key={x+1}>{x+1}</option>
                                            ))}
                                        </select>
                                    </div>
                        <button onClick={addToCartHandler(product._id, qty)} disabled={product.countInStock === 0} className="px-2 py-4 bg-pink-400 hover:bg-pink-300 hover:shadow-md text-white shadow-sm rounded-sm text-center my-4">Add to Cart</button>
                    </div>
                </div>
                )
            }
        </div>
            
    )
}

export default ProductScreen

非常奇怪的是,如果您单击主页上的图像,它将进入购物车。如果您点击主页上的产品名称,它会将商品添加到购物车并进入购物车。

图像或产品名称的链接引用没有区别。我不知道是什么导致了这个问题?

Homescreen > product.js

import Rating from './Rating'
import {Link} from 'react-router-dom'

const Product = ({product}) => {
    return (
        <div className="card rounded shadow flex md:flex-col items-center overflow-hidden ">
            <Link to={`/products/${product._id}`}>
                <img className="mx-4 my-1 h-60 md:h-50 py-2 object-contain" src={product.image} alt={product.name} />
            </Link>
            <div className="py-4 px-4 mx-4 md:mx-2">
                <Link to={`/products/${product._id}`} className="block h-28 font-light">{product.name}</Link>
                <span className="block text-lg mb-4 font-medium">${product.price.toFixed()}</span>
                <Rating product={product} />
                <button className="px-6 py-4 my-4 min-w-full bg-pink-400 hover:bg-pink-300 hover:shadow-md text-white shadow-sm rounded-sm block">Add to Cart</button>
            </div>
        </div>
    )
}

export default Product

我所知道的是,如果我去掉 productScreen.js 上“添加到购物车”按钮上的 onClick,重定向问题就会停止。

标签: reactjsreduxreact-redux

解决方案


您设置 onclick 的方式onClick={addToCartHandler(product._id, qty)} 是立即调用该方法。

为防止您必须将其包装在箭头函数中:

onclick={() => addToCartHandler(product._id, qty)}

在这里你可以在官方文档中准确地看到你的情况

这是有关将参数发送到处理程序的更多信息


推荐阅读