useContext:组件调用在我创建上下文的文件中定义的函数的默认值



创建了一个文件CartContext.tsx:

import React, { useState } from "react";
import { Product } from "../models/ProductModel";
interface CartContextValue {
cart: Product[];
addOneProductToCart: (product: Product) => void;
removeOneProductFromCart: (productId: number) => void;
deleteAllProductsFromCart: () => void;
}
export const CartContext = React.createContext<CartContextValue>({
cart: [],
addOneProductToCart: (product: Product) => {}, <----- **This runs in ShopPage**
removeOneProductFromCart: (productId: number) => {},
deleteAllProductsFromCart: () => {},
});
export const CartProvider: React.FC = ({ children }) => {
const [cart, setCart] = useState<Product[]>([]);
const addOneProductToCart = (product: Product) => { <----- **This should run instead!**
setCart([...cart, product]);
};
const removeOneProductFromCart = (productId: number) => {
const updatedCart = cart.filter((product) => product.id !== productId);
setCart(updatedCart);
};
const deleteAllProductsFromCart = () => {
setCart([]);
};
return (
<CartContext.Provider
value={{
cart,
addOneProductToCart,
removeOneProductFromCart,
deleteAllProductsFromCart,
}}
>
{children}
</CartContext.Provider>
);
};

我在App.js中使用提供者,这样我的所有组件都可以访问数据:

import { Route } from "react-router-dom";
import { IonApp, IonRouterOutlet, setupIonicReact } from "@ionic/react";
import { IonReactRouter } from "@ionic/react-router";
import { NavBar } from "./components/NavBar/NavBar";
import "@ionic/react/css/ionic.bundle.css";
import { useContext } from "react";
/* Pages */
import { UploadPage } from "./pages/UploadPage";
import { HomePage } from "./pages/HomePage";
import { ShopPage } from "./pages/ShopPage";
import { WatchVideoPage } from "./pages/WatchVideoPage";
import { LoginPage } from "./pages/LoginPage";
import { SuccessPurchasePage } from "./pages/SuccessPurchasePage";
import CancelPurchasePage from "./pages/CancelPurchasePage";
import { RegisterPage } from "./pages/RegisterPage";
import { CartContext } from "./state/CartContext";
// Custom styles
import "./theme/variables.css";
import "./theme/styles.css";
setupIonicReact();
const App: React.FC = () => {
**const {
cart,
addOneProductToCart,
removeOneProductFromCart,
deleteAllProductsFromCart,
} = useContext(CartContext);**

return (
<IonApp>
**<CartContext.Provider
value={{
cart,
addOneProductToCart,
removeOneProductFromCart,
deleteAllProductsFromCart
}}
>**
<IonReactRouter>
<NavBar />
<IonRouterOutlet>
<Route exact path="/" component={HomePage} />
<Route path="/video/:name" component={WatchVideoPage} />
<Route exact path="/login" component={LoginPage} />
<Route exact path="/register" component={RegisterPage} />
<Route exact path="/upload" component={UploadPage} />
<Route exact path="/success" component={SuccessPurchasePage} />
<Route exact path="/cancel" component={CancelPurchasePage} />
<Route exact path="/shop" render={() => <ShopPage />} />
</IonRouterOutlet>
</IonReactRouter>
**</CartContext.Provider>**
</IonApp>
);
};
export default App;

我有一个组件/页面,我想在其中添加一个产品到购物车中,这是在我创建ShopPage.tsx的上下文中:

import {
IonPage,
IonContent,
IonHeader,
IonTitle,
IonToolbar,
IonCard,
IonCardHeader,
IonCardTitle,
IonCardContent,
IonGrid,
IonRow,
IonCol,
IonButton,
IonSpinner,
} from "@ionic/react";
import { useContext } from "react";
import useProducts from "../hooks/useProducts";
import { Product } from "../models/ProductModel";
import { CartContext } from "../state/CartContext";
export const ShopPage = () => {
const [products, isLoading, isError] = useProducts();
**const { addOneProductToCart } = useContext(CartContext);**

if (isLoading) {
return <IonSpinner name="circular" />;
}
if (isError) {
return <h1>Could not get items...</h1>;
}
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>Shop</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent>
<div className="ion-padding-horizontal ion-padding-top">
<h1 className="ion-no-margin">Shop</h1>
</div>
<IonGrid>
<IonRow>
{Array.isArray(products) &&
products.map((product: Product) => {
return (
<IonCol
key={product.id}
size="12"
size-sm="12"
size-md="6"
size-lg="4"
>
<IonCard>
<img src={product.image} alt="Product" />
<IonCardHeader>
<IonCardTitle>{product.name}</IonCardTitle>
</IonCardHeader>
<IonCardContent>
<p>{product.description}</p>
<IonButton
className="float-right ion-margin-bottom"
color="dark"
**onClick={() => addOneProductToCart(product)}**
>
Buy
</IonButton>
</IonCardContent>
</IonCard>
</IonCol>
);
})}
</IonRow>
</IonGrid>
</IonContent>
</IonPage>
);
};

购物车没有更新。

我不明白必须在App.js中使用useContext然后将值传递给提供程序的意义。这很令人困惑。一定是我误解了什么。

未测试,但试试这个!应该工作:

  1. 删除这一行
import { CartContext } from "./state/CartContext"
  1. CartProvider添加导入

<CartContext.Provider
value={{
cart,
addOneProductToCart,
removeOneProductFromCart,
deleteAllProductsFromCart
}}>

把这个

<CartProvider>
**Rest of code**
</CartProvider>

相关内容

  • 没有找到相关文章

最新更新