Simple storage scheme based on React Hooks/Redux
The characteristics of
- Simple, a total of 4 objects, 2 for configuring global state and 2 for reading and updating state
- Support web,node(SSR environment), Taro micro channel and other small program state management
- Support for redux DevTool tracking status
The installation
NPM NPM/yarn
$ npm install --save simple-redux-store
$ yarn add simple-redux-store
Copy the code
use
1. Create a Store to provide a global store through the Provider
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider, configureStore } from 'simple-redux-store';
import App from './App';
// Initial state
const initialState = { name: 'name'.age: 1 };
/ / create a store
// The first argument is passed to the initial application state (if any).
// When the second argument is developed, passing true can track the status of the redux-devtool. Passing false disables the redux-devtool
const store = configureStore(initialState, true);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>.document.getElementById('root'));Copy the code
At this point, you can view the initial state with the redux devtool
2. Read the status and update the store
- Use the useSelector to select the desired state
- Use useUpdateStore to update the global status
import React from 'react';
import { useSelector, useUpdateStore } from 'simple-redux-store';
export default function App() {
return (
<div>
<NameComp />
<AgeComp />
</div>
);
}
// Name component
function NameComp() {
// Get the status update function
const updateStore = useUpdateStore();
// Get the status
const { name } = useSelector((s) = > s.app);
return <div onClick={()= > updateStore({ name: 'name' + Math.random() })}>hello {name} </div>;
}
// The age component
function AgeComp() {
const updateStore = useUpdateStore();
const { age } = useSelector((s) = > s.app);
return <div onClick={()= > updateStore({ age: age + 1 })}>you are {age} years old </div>;
}
Copy the code
Click on the name component to see the status change and the component update