zoukankan      html  css  js  c++  java
  • [React] Improve developer experience for accessing context with a custom React hook

    In this lesson, we create a custom hook that wraps the useContext hook and returns its value, as well as more useful error messaging if a context provider is missing. This simple addition brings very elegant ergonomics to access context from any component.

    providers/app-state.js

    import React, { createContext, useContext, useState } from "react";
    
    // Context
    const AppStateContext = createContext();
    
    // Provider
    export function AppStateProvider({ children }) {
      const [searchValue, setSearchValue] = useState("");
      const [shortList, setShortList] = useState([]);
    
      // The context value object
      const value = {
        searchValue,
        setSearchValue,
        shortList,
        setShortList
      };
    
      return (
        <AppStateContext.Provider value={value}>
          {children}
        </AppStateContext.Provider>
      );
    }
    
    // Custom hook
    export function useAppState() {
      const context = useContext(AppStateContext);
      if (!context) {
        throw new Error(
          "You probably forgot the <AppStateProvider> context provider!"
        );
      }
      return context;
    }

    Provider it:

    // index.js
    // React
    import React from "react";
    import ReactDOM from "react-dom";
    
    // CSS
    import "normalize-css";
    import "./css/styles.css";
    
    // Components
    import App from "./App";
    import { NamesProvider } from "./providers/names";
    import { AppStateProvider } from "./providers/app-state";
    
    ReactDOM.render(
      <React.StrictMode>
        <NamesProvider>
          <AppStateProvider>
            <App />
          </AppStateProvider>
        </NamesProvider>
      </React.StrictMode>,
      document.getElementById("root")
    );

    Consume it:

    import React from "react";
    
    import { NamesList } from "./names-list";
    import { useNames } from "../providers/names";
    import { useAppState } from "../providers/app-state";
    
    export function NamePicker() {
      const names = useNames();
      const { searchValue, shortList, setShortList } = useAppState();
    
      const filteredNames = names
        .filter(entry =>
          entry.name.toLowerCase().includes(searchValue.toLowerCase())
        )
        .filter(entry => !shortList.includes(entry.id));
      function addToShortList(id) {
        setShortList([...shortList, id]);
      }
    
      return <NamesList namesList={filteredNames} onItemClick={addToShortList} />;
    }
  • 相关阅读:
    使用JQuery实现延迟加载UserControl
    VisualStudio中的列选择
    SQL SERVER 2008 CTE生成结点的FullPath
    woocommerce独立站建站
    Java NIO使用及原理分析(二)
    java.io学习总结 转载
    java io与装饰器模式
    函数式思维: 不变性
    函数式思维: 运用函数式思维,第2 部分
    maven添加非官方jar包到本地库(maven: install an external jar into local maven repository)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12752361.html
Copyright © 2011-2022 走看看