npm install redux-react-hook --save
使用了react提供的Context(上下文)功能,给顶层组件Provide传入了store对象,绑定到上下文
程序入口
import {StoreContext} from 'redux-react-hook';
ReactDOM.render(
<StoreContext.Provider value={store}>
<App />
</StoreContext.Provider>,
document.getElementById('root'),
);
useDispatch、useMappedState组件中使用
useDispatch
:读取StoreContext,返回dispatch。
useMappedState
:一个自定义的hook,用来订阅reducer里的状态 (同步、异步都可)
import React,{useEffect,useCallback} from 'react'
import {useDispatch, useMappedState} from 'redux-react-hook';
import {getCustomerRole} from '../../store/actions/customer'
export function DeleteButton({index}) {
// 定义一个 mapState函数
const mapState = useCallback(
state => ({
roleList: state.customer.roleList
}),
[],
);
// 获取store中的数据
const {roleList} = useMappedState(mapState);
// 从store中读取dispatch
const dispatch = useDispatch();
useEffect(()=>{
//dispatch派发action获取数据
dispatch(getCustomerRole())
},[dispatch,roleList,getCustomerRole])
return (
<Table dataSource={roleList}
columns={columns} bordered
rowKey={record => record.id}
/>
);
}
StoreContext
获取上下文的store对象
此方法可以获取store中的同步值
异步无法动态更新
import React,{useEffect,useContext} from 'react'
import {StoreContext} from 'redux-react-hook';
function test(){
// 获取上下文的store对象
const store = useContext(StoreContext)
let {dispatch,getState ...other}=store;
//获取store的数据 在不同组件修改数据会动态改变
let storeState=getState();
let { roleList }=storeState.customer ;
useEffect(()=>{
//dispatch派发action获取数据
dispatch(getCustomerRole())
},[dispatch,roleList,getCustomerRole])
return (
<Table dataSource={roleList}
columns={columns} bordered
rowKey={record => record.id}
/>
);
}