码迷,mamicode.com
首页 > 数据库 > 详细

[React] Improve developer experience for accessing context with a custom React hook

时间:2020-04-22 16:57:54      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:UNC   you   lis   picker   any   styles   sim   iss   ons   

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} />;
}

 

[React] Improve developer experience for accessing context with a custom React hook

标签:UNC   you   lis   picker   any   styles   sim   iss   ons   

原文地址:https://www.cnblogs.com/Answer1215/p/12752361.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!