react redux异步请求

1,创建store

javascript 复制代码
//store/modules/channelStore.js
import { createSlice } from "@reduxjs/toolkit"
import axios from "axios"

const channelStore = createSlice({
  name: 'channel',
  initialState: {
    channelList: []
  },
  reducers: {
    setChannels (state, action) {
      state.channelList = action.payload
    }
  }
})

// 异步请求部分
const { setChannels } = channelStore.actions
// 单独封装一个函数 在函数内部return一个新函数
const fetchChannelList = () => {
  return async (dispatch) => {
    // 调用异步请求
    const res = await axios.get('http://geek.itheima.net/v1_0/channels')
    // 调用同步actioncreate
    dispatch(setChannels(res.data.data.channels))
  }
}

export { fetchChannelList }

const reducer = channelStore.reducer

export default reducer

2,导入子模块

javascript 复制代码
// store/index.js
import { configureStore } from "@reduxjs/toolkit"
// 导入子模块reducer
import channelReducer from "./modules/channelStore"

const store = configureStore({
  reducer: {
    channel: channelReducer
  }
})

export default store

3,使用

javascript 复制代码
import { fetchChannelList } from "./store/modules/channelStore"
import { useEffect } from "react"

function App () {
  const { channelList } = useSelector(state => state.channel)
  // 得到dispatch函数
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(fetchChannelList())
  }, [dispatch])
  
  return (
    <div className="App">
      <ul>
        {channelList.map(item => <li key={item.id}>{item.name}</li>)}
      </ul>
    </div>
  )
}
相关推荐
巴巴博一15 分钟前
2026 最新:Trae / Cursor 一键接入 taste-skill 完整教程(让 AI 前端告别“AI 味”)
前端·ai·ai编程
kyriewen21 分钟前
半夜三点线上崩了,AI替我背了锅——用AI排错,五分钟定位三年老bug
前端·javascript·ai编程
kyriewen39 分钟前
我让 AI 当了 24 小时全年无休的“毒舌考官”
前端·ci/cd·ai编程
hexu_blog1 小时前
vue+java实现图片批量压缩
java·前端·vue.js
IT_陈寒1 小时前
为什么你应该学习JavaScript?
前端·人工智能·后端
lifejump2 小时前
Empire(帝国)CMS 7.5 XSS注入
前端·安全·xss
无风听海2 小时前
OAuth 2.0 前端通道与后端通道深入剖析
前端·oauth
sakiko_2 小时前
UIKit学习笔记8-发送照片、拍摄照片并发送
前端·swift·uikit
_code_bear_2 小时前
OpenSpec CLI 与 OPSX 工作流说明
前端·后端·架构