- React state management – a lightweight react state management tool
- Applies to functional components
- React Hook API useContext, useReducer implementation
Structure | – SRC | – store | — — — — – the userInfo. Js | — — — — – mineInfo. Js | — — — — — index. The js | – App. Js
Const userInfo = {nameSpace: '', // name state: {}, // data getter: {}, // count attributes (equivalent to vuex getters) reducer: Vuex mutations effects: {} // redux actions effects: {}Copy the code
Create – createStore
/** * Import {createStore} from 'hokx' const mineInfo = {nameSpace: 'mineInfo', state: { name: 'hokx', age: 18, salary: 20 }, getter: { totalAssets(state){ return state.age * state.salary }, }, reducer: { setName(state, action){ state.name = action.name return {... state} } }, effects: { async getData({state,put}, action){ const { data } = await axios({ method: 'GET', url: '/user.json' }) put({type:'setName', name: data.name}) } } } const reducer = [mineInfo] const Provider = createStore(reducer) export default ProviderCopy the code
Injection – the Provider
import Provider from './store'
ReactDOM.render(
<Provider>
<App />
</Provider>,
document.getElementById('root')
);
Copy the code
Using the — useStore
/** * Retrieve the data stored in the store via the hook useStore * @param {nameSpace} name * */ import React from 'React' import {useStore} from 'hokx' export default (props) => { const {state, dispatch} = useStore(nameSpace) let handle = () => { dispatch({type: '', data: ''}) } return ( <div onClick={handle}>{JSON.stringify(state)}</div> ) }Copy the code
Evaluate the property — useGetter
/** * Retrieve store calculated property via hook useGetter * @param {nameSpace} name * @return Returns store getter */ import {useGetter} from 'hokx' const getter = useGetter('mineInfo') console.log(getter.totalAssets)Copy the code
Global – store
/** * If you want to not use state, getter, dispatch * in a component or just perform dispatch in a component, / import Store from 'hokx' store.[nameSpace]State store.[nameSpace]Dispatch({type: '', data: ' '}) store. [nameSpace] Getter. Values: store.userInfoState.name store.userInfoDispatch() store.userInfoGetter.totalAssetsCopy the code
LocalStorage — localStorage/sessionStorage
Const reducer = {nameSpace: '', localStorage: true, // Open state local localStorage} or const reducer = {nameSpace: ", sessionStorage: true, // Enable the current state of local sessionStorage}Copy the code
NPM address: hokx source address: github shopping cart demo source address: github shopping cart