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} />;
    }
  • 相关阅读:
    发现个atan2的正确使用方式
    Forward+ Shading架构
    fatal: unable to connect to gitee.com: gitee.com[0: 180.97.125.228]: errno=Unknown error 解决方案
    HDFS HA(高可用性)集群规划
    如何使用RTP引擎对语音编码进行转码
    关于 Angular 应用 tsconfig.json 中的 target 属性
    浅谈 Orbeon form builder 的权限控制
    关于 Angular 应用 tsconfig.json 中的 lib 属性
    orbeon form 通过 url 的方式同第三方应用集成的开发明细
    orbeon form 的配置介绍
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12752361.html
Copyright © 2011-2022 走看看