一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第2天,点击查看活动详情。
首先,要在TypeScript中使用Redux,就要先了解React里Redux在JS中的使用,不了解原生语法,更别谈TS中的使用了。
Redux-Thunk的实现过程
1.在组件里
//使用useEffect监听数据的变化,当数据发生变化时,会在useEffect函数里发送异步请求再次获取数据
import React, { useEffect } from 'react'
//useDispatch用于发送异步请求,其内部会调用store/actions中的方法获取数据
//useSelector用于调用存储于redux中的数据
import { useDispatch, useSelector } from 'react-redux
语法:
import {RootState} from '@/store/index' //定义了Sate参数的数据类型
const dispatch=useDispatch()
//获取存储于Redux中的数据
const 数据名=useSelector((state:RootStateType)=>state.数据名)
useEffect(()=>{
dispatch(store/actions中的方法)
},[dispatch])
2.在store/actions中发送异步请求获取数据
语法:
import axios from 'axiso' //要先下 axios 包
import {RootThunkAction} from '@/store/index'
export const 函数名 = () : RootThunkAction => {
return async (dispatch) => {
const res= await axios.请求方式('接口地址')
dispatch({
type:'',
初始值函数名(initState):所需的数据
})
}
}
3.在Reducers中将获得的数据存储到Redux中
语法:
import {ChannelActionType} from '@/store/index'
type 类型1 = 保存到 Redux 中的数据类型
const initState:类型1={
需要存储到Redux中的数据初始值
}
const 函数名=(state:要和存储到Redux中的数据类型一致,action:ChannelActionType):返回值类型:类型1=>{
if(action.type===要与ChannelActionType){
return state
}
}
//将这个函数暴露出去
export default 函数名
4.毕竟时TS嘛,肯定要定义好数据类型
在sotre/index.ts中
语法:
import { applyMiddleware, createStore } from 'redux'
import reducer from './reducers'
import thunk, { ThunkAction } from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
//store.getStore()可以拿到Redux中存储的所有数据state
export const store = createStore(reducer, composeWithDevTools(applyMiddleware(thunk)))
//useSeletor中state的数据类型
export type RootStateType=ReturnType<typeof store.getState>
export type Channels={
id:number,
name:string,
}
//同步修改redux数据时Redux的数据类型(action的数据类型)
export type ChannelActionType=
| {type:'channel/SET_CHANNEL',initState:Channels[]}
export type RootAction=ChannelActionType
//异步请求返回数据的数据类型
export type RootThunkAction = ThunkAction<void, RootStateType, unknown, RootAction>
大致流程图如下: