如何访问Navbar
等其他组件中的basket
以显示购物车的内容?如果代码中有任何逻辑错误,请纠正我。提前谢谢。
const cartReducer = (state, action) => {
switch (action.type) {
// other cases
case 'INITIALIZE_CART':
return action.payload;
default:
return state;
}
};
const initialState = {
basket: []
};
const CartContext = createContext();
const CartProvider = ({ children }) => {
const [state, dispatch] = useReducer(cartReducer, initialState);
useEffect(() => {
axios.get('userdetails', {
headers: { "Authorization": localStorage.getItem('token') }
}).then(res => {
console.log(res)
dispatch({
type: 'INITIALIZE_CART',
payload: {
...initialState,
basket: res.data.cart
}
})
})
}, []);
return (
<CartContext.Provider value={{ state, dispatch }}>
{children}
</CartContext.Provider>
);
};
export const useStateValue = () => useContext(CartContext)
export default CartProvider
导入CartState并将其用于访问状态和传递动作
import { CartState } from '../Cart/StateProvider'
const [{ basket }, dispatch] = CartState()