Last active
April 20, 2022 14:00
-
-
Save ifyour/97163a5535488339d6d739b21382dfec to your computer and use it in GitHub Desktop.
使用 context API 管理状态 Demo: https://codesandbox.io/s/makestore-react-context-easiest-solution-4hiu4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
export function makeStore({actions}) { | |
// Make a context for the store | |
const context = React.createContext(); | |
// Make a provider that takes an initialValue | |
const Provider = ({initialValue = {}, children}) => { | |
// Make a new state instance | |
const [state, setState] = React.useState(initialValue); | |
// Bind the actions with the old state and args | |
const boundActions = React.useMemo( () => { | |
let some = {} | |
Object.keys(actions).forEach((actionName) => { | |
some[actionName] = (...args) => () => | |
setState((old) => actions[actionName](old, ...args)); | |
}); | |
some.setState = setState; | |
return some | |
},[]) | |
// Memoize the context value to update when the state does | |
const contextValue = React.useMemo(() => ({state, ...boundActions}), [state,boundActions]) | |
// const contextValue = React.useMemo(() => [state, boundActions], [state]); | |
// const contextValue = React.useMemo(() => [state, boundActions, setState], [state]); | |
// Provide the store to children | |
return <context.Provider value={contextValue}>{children}</context.Provider>; | |
}; | |
// A hook to help us consume the store | |
const useStore = () => React.useContext(context); | |
return [Provider, useStore]; | |
} | |
// src: https://gist.github.com/tannerlinsley/699aae70417da8e0c11f7fb7876c49b8 | |
// src: https://gist.github.com/tannerlinsley/a78598f751ef0d9f9d8d9973e5ec9ff6 | |
// src: https://gist.github.com/tannerlinsley/d666b1d9974d7277c74b6fd815986164 | |
// src: https://gist.github.com/tannerlinsley/490272e89c9a822eb3819e97dd5759c1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment