- 小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
前言
redux是我们熟知的状态管理工具,但是对于非大型复杂状态管理来说过于臃肿,react提供了hook:useContext + useRudex, 可以帮我们实现redux的功能
必备条件
- 已创建好react项目,可以用(creat-react-app)的ts模版
- React的版本 大于 v16.8
- 熟悉react的基本hook写法
创建store文件夹
文件夹内新建 index.tsx
import { createContext } from 'react'
export interface StateProps {
userInfo: {
name?: string
}, // 用户信息
}
export const initState: StateProps = { userInfo: {name: 'name'}}
interface IContextProps {
state: {
userInfo: {
name?: string
}
};
dispatch: ({type, payload}:{type:string, payload: object}) => void;
}
export const GlobalContext = createContext({} as IContextProps)
创建reducer文件夹
文件夹内新建 index.ts
export interface StateProps {
userInfo: {
name: string
}, // 用户信息
}
const gloReducer = (state: StateProps, action: any) => {
switch (action.type) {
case 'updateUserInfo':
return {
...state,
userInfo: action.payload,
}
default:
return state
}
};
export default gloReducer;
在cra生成的src内 index.tsx内增加 (挂在在根部)
import React, { useReducer } from 'react';
import ReactDOM from 'react-dom';
import './global.less';
import App from './pages/App';
import reportWebVitals from './reportWebVitals';
import { GlobalContext, initState } from './store'
import gloReducer from './reducer'
const Root: React.FC = () => {
const [state, dispatch] = useReducer(gloReducer, initState)
return (
<GlobalContext.Provider value={{state, dispatch}}>
<App />
</GlobalContext.Provider>
)
}
ReactDOM.render(
<React.StrictMode>
<Root/>
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
调用
在随便某个子页面内
import React, { useContext } from 'react'
import { Button } from 'antd'
import { GlobalContext } from '@/store'
const Home: React.FC<{}> = (props) => {
const {state, dispatch} = useContext(GlobalContext)
return (
<div>
<Button onClick={() => {dispatch({type: 'updateUserInfo', payload: {name: '1112222'}})}}>{state.userInfo.name}</Button>
</div>
)
}
export default Home
完成
有问题欢迎留言探讨