react redux异步哀求

[复制链接]
发表于 2026-2-3 08:32:17 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
1,创建store
  1. //store/modules/channelStore.js
  2. import { createSlice } from "@reduxjs/toolkit"
  3. import axios from "axios"
  4. const channelStore = createSlice({
  5.   name: 'channel',
  6.   initialState: {
  7.     channelList: []
  8.   },
  9.   reducers: {
  10.     setChannels (state, action) {
  11.       state.channelList = action.payload
  12.     }
  13.   }
  14. })
  15. // 异步请求部分
  16. const { setChannels } = channelStore.actions
  17. // 单独封装一个函数 在函数内部return一个新函数
  18. const fetchChannelList = () => {
  19.   return async (dispatch) => {
  20.     // 调用异步请求
  21.     const res = await axios.get('http://geek.itheima.net/v1_0/channels')
  22.     // 调用同步actioncreate
  23.     dispatch(setChannels(res.data.data.channels))
  24.   }
  25. }
  26. export { fetchChannelList }
  27. const reducer = channelStore.reducer
  28. export default reducer
复制代码
2,导入子模块
  1. // store/index.js
  2. import { configureStore } from "@reduxjs/toolkit"
  3. // 导入子模块reducer
  4. import channelReducer from "./modules/channelStore"
  5. const store = configureStore({
  6.   reducer: {
  7.     channel: channelReducer
  8.   }
  9. })
  10. export default store
复制代码
3,利用
  1. import { fetchChannelList } from "./store/modules/channelStore"
  2. import { useEffect } from "react"
  3. function App () {
  4.   const { channelList } = useSelector(state => state.channel)
  5.   // 得到dispatch函数
  6.   const dispatch = useDispatch()
  7.   useEffect(() => {
  8.     dispatch(fetchChannelList())
  9.   }, [dispatch])
  10.   
  11.   return (
  12.     <div className="App">
  13.       <ul>
  14.         {channelList.map(item => <li key={item.id}>{item.name}</li>)}
  15.       </ul>
  16.     </div>
  17.   )
  18. }
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表