因此,我试图在删除购物车中的项目后再次呈现页面,这样购物车页面就不会显示该项目。
我正在尝试使用useEffect和useState,如下所示,cartItem状态正在设置,但是页面不会重新呈现。
const CartItem = ({item}) =>
{
const {line_items} = useCartState() // to get cart details
const [cartItems,setCartItems] = useState([{}])
const cartOnLoad = async() =>{
setCartItems(line_items)
}
useEffect(() => {
cartOnLoad()
console.log('from useEffect',cartItems)
},[cartItems])
const removeItem = async() => {
await commerce.cart.remove(item.id)
console.log(line_items)
await cartOnLoad()
console.log('from remove items', cartItems)
}
if(!item.line_total) return <p>'Loading...'</p> // We need to find an alternative to this
else
{
return (
<div className="border-t border-b border-gray-200 divide-y divide-gray-200">
<div className="flex py-6 sm:py-10">
<div className="flex-shrink-0">
<img
src={item.image.url}
alt={item.name}
className="w-24 h-32 rounded-md object-center object-cover sm:w-48 sm:h-64"
/>
</div>
<div className="ml-4 flex-1 flex flex-col justify-between sm:ml-6">
<div className="relative pr-9 sm:grid sm:grid-cols-2 sm:gap-x-6 sm:pr-0">
<div>
<div className="flex justify-between">
<h3 className="text-sm">
<a href="#" className="font-medium text-gray-700 hover:text-gray-800">
{item.name}
</a>
</h3>
</div>
<p className="mt-1 text-sm font-medium text-gray-900">{item.price.formatted_with_symbol}</p>
</div>
<div className="absolute top-0 right-0">
<button type="button" className="-m-2 p-2 inline-flex text-gray-400 hover:text-gray-500"
onClick={removeItem}>
<span className="sr-only">Remove</span>
<XIcon className="h-5 w-5" aria-hidden="true" />
</button>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default CartItemuseCartState()是这里的上下文
他们不会在这里重新呈现任何想法吗?谢谢!
下面是上下文
import {createContext, useEffect, useContext, useReducer} from 'react'
import {commerce} from '../../lib/commerce'
//need to correct this file to be a tsx file in the future
//Provides a context for Cart to be used in every page
const CartStateContext = createContext()
const CartDispatchContext = createContext()
const SET_CART = "SET_CART"
const initialState = {
total_items: 0,
total_unique_items: 0,
subtotal:[],
line_items: [{}]
}
const reducer = (state,action) => {
switch(action.type){
case SET_CART:
return { ...state, ...action.payload }
default:
throw new Error(`Unknown action: ${action.type}` )
}
}
export const CartProvider = ({children}) => {
const [state, dispatch] = useReducer(reducer, initialState)
const setCart = (payload) => dispatch({type: SET_CART, payload})
useEffect(() => {
getCart()
},[])
const getCart = async() => {
try {
const cart = await commerce.cart.retrieve()
setCart(cart)
} catch (error){
console.log("error")
}
}
return (
<CartDispatchContext.Provider value = {{setCart}}>
<CartStateContext.Provider value = {state}>
{children}
</CartStateContext.Provider>
</CartDispatchContext.Provider>
)
}
export const useCartState = () => useContext (CartStateContext)
export const useCartDispatch = () => useContext (CartDispatchContext)发布于 2022-07-12 22:15:17
在发生反应时,避免修改数组,生成一个新数组以保持不变性。
const removeItem = async (itemId) => {
await commerce.cart.remove(itemId)
const updatedCart = [...cartItems];
const itemIndex = updatedCart.findIndex(
(item) => item.id === itemId
);
if (itemIndex >= 0) {
updatedCart.splice(itemIndex, 1);
setCartItems(updatedCart);
} else {
throw new Error();
}
};https://stackoverflow.com/questions/72958855
复制相似问题