react hooks + typescript +中使用reudx

ts 中因为要定义很多 类型 所以不多说直接上代码
在入口文件中:

import { Provider } from "react-redux";
import store from "./redux";
<Provider store={store}>
          <Routes />
        </Provider>

下面是redux中的配置:


## combineReducers中配置:
import { getDefaultType } from "要引入的地址";
interface getDefaultRedecerType {
  getDefault: Array<getDefaultType>;
}
const initState: getDefaultRedecerType = {
  getDefault: [],
};
const getDefaultRedecer = (
  prevState: getDefaultRedecerType = initState,
  action: any
): getDefaultRedecerType => {
  let { type, payload } = action;
  switch (type) {
    case "getDefault":
      return {
        getDefault: payload,
      };
    default:
      return prevState;
  }
};
export default getDefaultRedecer;

## redux中代码:

import { applyMiddleware, combineReducers, compose, createStore } from "redux";
import thunk from "redux-thunk";
import getDefaultRedecer from '要引入的地址'

const composeEnhancers =
  (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

// 合并reducers
const reducer = combineReducers({
  getDefault:getDefaultRedecer
});

export type RootState = ReturnType<typeof reducer>;
// 生成store
const store = createStore(reducer, composeEnhancers(applyMiddleware(thunk)));

export type AppDispatch = typeof store.dispatch;

export default store;

组件中配合useSelector以及useDispatch使用代替以前的connect

//派发的参数
  const dispatch:AppDispatch = useDispatch()
  // 监听派发器 避免重新渲染报错
  useEffect(()=>{
    dispatch({
      type:"getDefault",
      payload:getDefault
    })
  },[getDefault])
// 得到从redux中共享的默认地址的参数
  const getDefault = useSelector((State:RootState)=>State.getDefault.getDefault)

action中的类型自己可以定义,在这里我直接使用的any管理
如果有错误请多多指正

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值