Skip to content

Instantly share code, notes, and snippets.

@JerryC8080
Created January 6, 2021 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JerryC8080/91522f750e06bf08bad5d9424f858035 to your computer and use it in GitHub Desktop.
Save JerryC8080/91522f750e06bf08bad5d9424f858035 to your computer and use it in GitHub Desktop.
simple store use 'useRedux' and 'useContext'
/**
* 简易 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 };
};
export default {};
// 简易 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