安装依赖
yarn add redux redux-react-hook shallowequal @types/shallowequal
redux-react-hook
是主角,对 react-redux
进行了二次封装,从而可以在 react-hook
中使用自如 redux-react-hook(官方文档)
shallowequal
的作用是在两个值(即和)之间进行浅等式比较,以确定它们是否相等。
改造项目
1.根目录下的
index.tsx
import React from 'react' import ReactDOM from 'react-dom' import { makeStore } from './redux/Store'; import { StoreContext } from 'redux-react-hook'; import App from './App' const store = makeStore() ReactDOM.render( <StoreContext.Provider value={store}> <App /> </StoreContext.Provider> , document.getElementById('root'))
其中引入
StoreContext
是为了全局保存store
2.根目录下建立
redux
的文件夹,并创建Reducers.tsx
和Store.tsx
的文件a.
Store.tsx
import reducer from './Reducers'; export function makeStore() { return createStore(reducer, { queryList: [] // 这里声明需要存储在redux中的变量 }) }
b.
Reducers.tsx
export default function reducer(state: any, action: any) { switch (action.type) { case "SET_QUERTLIST": { // 如果action的type为SET_QUERTLIST时通知redux修改queryList的值 return { ...state, queryList: action.queryList } } default: return state } }
3.下面就可以愉快的使用了(实战内容)
import React, { useCallback, useEffect, useMemo, useState, } from 'react' import shallowEqual from 'shallowequal' import { useDispatch, useMappedState } from 'redux-react-hook'; // 引入redux-react-hook中useDispatch和useMappedState的方法,其中useMappedState是获取store中的值,useDispatch是修改store中的值的方法 const _queryList = [{ name: 'query0', id: 0 }]; // 这里初始化一个变量,待会儿修改store中queryList的值 function QueryList({ onResize, setqueryItemMsg, setSqlTable }: QueryEditorProps) { const mapState = useCallback( state => ({ queryList: state.queryList }),[]); } const { queryList } = useMappedState(mapState, shallowEqual) // 通过以上两步就已经对新变量queryList赋于了store中queryList的值了(就是拿到了值) const dispatch = useDispatch(); useEffect(() => { setTimeout(() => { dispatch({ type: 'SET_QUERTLIST', queryList: _queryList }) }, 3000) }, []) // 这里模拟请求的3秒后对store中的queryList重新赋值 }
到这里就结束了,总体来说相对于 react-redux
变化不大。
That's all, thank you!