Created
January 6, 2021 09:18
-
-
Save JerryC8080/91522f750e06bf08bad5d9424f858035 to your computer and use it in GitHub Desktop.
simple store use 'useRedux' and 'useContext'
This file contains hidden or 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
/** | |
* 简易 Store | |
* | |
* 使用: | |
* | |
* 1. 使用 Provider HOC | |
* | |
* ```jsx | |
* <Provider> | |
* <Child /> | |
* </Provider> | |
* ``` | |
* | |
* 2. useStore in child.tsx | |
* | |
* ```javascript | |
* const {store, setStore} = useStore(); | |
* | |
* return ( | |
* <input | |
* value={store.person.name} | |
* onClick={(values) => setStore({key: 'person.name', values})} | |
* /> | |
* ) | |
* | |
* ``` | |
*/ | |
import React, { createContext, useContext, useReducer } from 'react'; | |
import initialState from './initial-state'; | |
import setter from './setter'; | |
export function reducer(state = initialState, action) { | |
const newState = { ...state }; | |
setter(newState, action.key, action.values); | |
return newState; | |
} | |
const StateContext = createContext<any>(initialState); | |
export const Provider = ({ children }) => { | |
return React.createElement( | |
StateContext.Provider, | |
{ value: useReducer(reducer, initialState) }, | |
children, | |
); | |
}; | |
export const useStore = () => { | |
const [store, setStore] = useContext(StateContext); | |
return { store, setStore }; | |
}; |
This file contains hidden or 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
export default {}; |
This file contains hidden or 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
// 简易 set | |
const setter = (obj, key, value) => { | |
const keys = key.split('.'); | |
const pres = keys.slice(0, -1); | |
const last = keys[keys.length - 1]; | |
const deepObj = | |
keys.length === 1 | |
? obj | |
: pres.reduce((curObj, curKey) => { | |
// eslint-disable-next-line no-param-reassign | |
if (!curObj[curKey]) curObj[curKey] = {}; | |
return curObj[curKey]; | |
}, obj); | |
deepObj[last] = value; | |
return obj; | |
}; | |
export default setter; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment