在React+TypeScript发请求的流程

376 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第7天,点击查看活动详情


大家好,我是大帅子,今天我们来讲一下在React+TypeScript发请求的流程,绝对良心,看完不会你来砍我,好了,话不多说,我们直接开始


我们就拿两个模块来说明 , 上一个案例我们讲了todos案例,但是是假数据,我们并没有真正的发送请求,所有这次我们来一个可以发送请求的案例跟着一起讲,这样就比较好理解一点
我们需要在app下面把下面的两个模块链入
import React from 'react'
import Channel from './components/Channel'
import NewsList from './components/NewsList'
import './styles/index.css'
export default function App() {
  return (
    <div className="app">
      <Channel></Channel>
      <NewsList></NewsList>
    </div>
  )
}

1. 我们先获取数据

import { getChannelList } from "/store/action/channel"

 const dispatch = useDispatch()
  useEffect(() => {
    dispatch(getChannelList())
  }, [dispatch])
  
 //RootState在/store/index.ts里面链入
const channel = useSelector((state: RootState) => state.channel)

2. 在/store/action/channel 设置处理函数

export function getChannelList(): RootThunkAction {
  return async (dispatch: any) => {
    const res = await axios.get('http://.........net/v1_0/channels')
    console.log(res)

    // 3. dispatch ChannelAction  问题: dispatch的时候没有提示
    dispatch({
      type: 'channel/getChannelList',
      payload: res.data.data.channels
    })
  }
}

3. 我们做处理 /store/reducers/channel

// initValue 的类型要在本模块里面定义 , action类型在 /store/index.ts里面定义
export default function channel(state = initValue, action: AtionType) {
  // console.log(state, action, 222);
  if (action.type === 'channel/getChannelList') {
    return { ...state, channelList: action.payload }
  }
  return state
}

4. 最后我们在/store/index.ts

const store = createStore(reducer, composeWithDevTools(applyMiddleware(thunk)))
import { createStore, applyMiddleware } from 'redux'
import thunk, { ThunkAction } from 'redux-thunk'

// 拿到了类型  //可以当做固定写法  组件里面的类型用
export type RootState = ReturnType<typeof store.getState>

// 每多发一个请求就多加一个类型
export type ActionType =
   {
    type: 'channel/getChannelList' // 字面量类型
    name: []
  }|
  {
  
  }


// 异步代码的 action   //ThunkAction <固定写法, 上面的类型, 固定写法,这里是第三步处理事件dispatch中间定义的>
export type RootThunkAction = ThunkAction<void, RootState, unknown, ActionType>

下面我附图一张

image.png


好了,这边已经给大家介绍到这里,以上是我自己的理解,讲的不好, 欢迎留言我这边一定会第一时间给大家解答,喜欢的可以点赞收藏,
🐣---->🦅        还需努力!大家一起进步!!!