react状态管理store用法一: 使用内置useContext
不借助redux,实现状态管理,修改引用数据时可能会有数据更新了,页面没更新的情况。安装immer来避免这个问题
npm install immer use-immer -S
store.tsx
/* eslint-disable max-statements-per-line */ import React, {createContext, useContext, useMemo} from 'react'; import {useImmer} from 'use-immer'; interface dataState { detailData?: any; currentId: string; dataSourceList: any[]; } interface updateData { setDetailData: (v: any) => void; setCurrentId: (v: any) => void; setDataSourceList: (v: any) => void; } interface ConfigStore { data: dataState; updateData: updateData; } const context = createContext<ConfigStore>({ data: { detailData: undefined, currentId: '1', dataSourceList: [] }, updateData: { setDetailData: () => {}, setCurrentId: () => {}, setDataSourceList: () => {} } }); const {Provider} = context; export const ConfigProvider: React.FC = ({children}) => { const [data, setData] = useImmer<dataState>({ detailData: undefined, currentId: '', dataSourceList: [] }); const updateData = useMemo(() => { return { setDetailData: (v: any) => { setData((draft: any) => { draft.detailData = v; }); }, setCurrentId: (v: any) => { setData((draft: any) => { draft.currentId = v; }); }, setDataSourceList: (v: any) => { setData((draft: any) => { draft.dataSourceList = v; }); } }; }, [setData]); return <Provider value={{data, updateData}}>{children}</Provider>; }; export const useConfigData = () => useContext(context);
配置
import {ConfigProvider} from './store'; // 在包裹的组件中配置使用 const ProviderConfig = (props) => { return ( <ConfigProvider> <MyComponent {...props} /> </ConfigProvider> ); }; export default ProviderConfig; // 全部组件中配置使用 import {ConfigProvider} from './store'; const APP = () => { return ( <ConfigProvider> <MyComponent /> </ConfigProvider> ); }; export default App;
使用
import {useConfigData} from './store'; const Mycomponent =() => { const { data: {currentId, dataSourceList}, updateData: {setCurrentId} } = useConfigData(); } const clickHangle = () => { setCurrentId('2') } return (<div onClick={clickHangle}> {currentId} </div>)