zoukankan      html  css  js  c++  java
  • [React] Use the React Context API to Globally Manage State

    Using React hooks like useState makes it easy to manage things like a shopping cart, but that state may only be available one instance at a time. What if we wanted that state to be available between multiple pages?

    We can take advantage of React's Context API which lets us extend our cart state by making that state available anywhere we want in the app.

    In our app, we want to move the cart from the Home page component to the header which requires us to use context. We will wrap our app in a CartContext.Provider and pass in cart from our cart hook. This will allow us to grab subtotal and checkout for the Nav component.

    If there is one state which both used in pageA and pageB, we can lift this state into Context, then it is availabel for both pageA & B

    A hook file, contains both Context and state.

    import { useState, useContext, createContext } from 'react';
    import { initiateCheckout } from '../lib/payments.js'
    import products from '../products.json';
    
    const defaultCart = {
      products: {}
    }
    
    export const CartContext = createContext();
    
    export function useCartState() {
    
      const [cart, updateCart] = useState(defaultCart);
    
      ...return {
        cart,
        subtotal,
        quantity,
        addToCart,
        checkout
      }
    
    }
    export function useCart() {
      const cart = useContext(CartContext);
      return cart;
    }

    index.js:

    function MyApp({ Component, pageProps }) {
      const cart = useCartState();
      return (
        <CartContext.Provider value={cart}>
          <Nav />
          <Component {...pageProps} />
        </CartContext.Provider>
      )
    }

    Uage:

    const Nav = () => {
      
        const { subtotal, checkout} = useCart();
    
      return (
        <nav className={styles.nav}>
          <p className={styles.navTitle}>
            Space Jelly Shop
          </p>
          <p className={styles.navCart}>
            <button onClick={checkout}>
              <FaShoppingCart /> ${subtotal}
            </button>
          </p>
        </nav>
      )
    }
    
    export default Nav;
  • 相关阅读:
    JavaScript-创建日志调试对象(面向对象实例)
    公有属性 公有方法(原型方法) 私有属性 私有方法 特权方法 静态属性 静态方法 对象字面量创建
    JS库创建
    无post按钮提交表单
    当浏览器窗口大小改变时,设置显示内容的高度
    单元测试(qunit)
    HTML定位(滚动条、元素,视口)定位
    document.compatMode(判断当前浏览器采用的渲染方式)
    jquery自定义方法
    jQuery选择器总结
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14358618.html
Copyright © 2011-2022 走看看