【发布时间】:2022-06-10 19:50:45
【问题描述】:
我正在使用 React 构建一个网站。假设有可以通过单击“添加到购物车”按钮添加到购物车的产品。现在,我只是尝试通过控制台在 reducer 中记录“操作”来访问每个“添加到购物车”按钮,但其中只有一个按钮可以被触发。这是产品的代码
function Product({id, title, image, price, rating}) {
//accepts props of each product
const [state, dispatch] = useStateValue()
const addToCart = () => {
dispatch({
type: "ADD_TO_CART",
item: {
id: id,
title: title,
image: image,
price: price,
rating: rating
}
})
}
return (
<div className='product'>
<div className="product-info">
<p>{title}</p>
<p className="product-price">
<small>$</small>
<strong>{price}</strong>
</p>
<div className="product-rating">
{Array(rating)
.fill()
.map((_, i) => (
<p>????</p>
))}
</div>
</div>
<img
src={image}
alt=""
/>
<button onClick={addToCart}>Add to cart</button>
</div>
)
}
这是我使用的减速器
export const initialState = {
cart: [],
}
const reducer = (state, action) => {
console.log(action);
switch(action.type) {
case 'ADD_TO_CART':
return{
...state,
cart: [...state.cart, action.item]
}
default:
return state;
}
}
我的网页中总共有 6 个产品,除了最后一个之外,没有一个产品在单击时会触发“console.log(action)”。 在主索引文件中,我使用此代码导入减速器
import reducer, { initialState } from './reducer';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<StateProvider initialState={initialState} reducer={reducer}>
<App />
</StateProvider>
</React.StrictMode>
);
我尝试为每个产品添加唯一值,以更正 z-index。没有改变。有人可以帮我吗?
【问题讨论】:
标签: javascript reactjs button