标签: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