当前位置: 首页 > news >正文

react redux异步请求

1,创建store

//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')// 调用同步actioncreatedispatch(setChannels(res.data.data.channels))}
}export { fetchChannelList }const reducer = channelStore.reducerexport default reducer

2,导入子模块

// store/index.js
import { configureStore } from "@reduxjs/toolkit"
// 导入子模块reducer
import channelReducer from "./modules/channelStore"const store = configureStore({reducer: {channel: channelReducer}
})export default store

3,使用

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>)
}

http://www.mrgr.cn/news/9177.html

相关文章:

  • Python计算机视觉 第3章-图像到图像的映射
  • 春游c++
  • Web3链上聚合器声呐已全球上线,开启区块链数据洞察新时代
  • HTML实现俄罗斯方块
  • 每天五分钟深度学习:从数学角度分析逻辑回归算法损失函数的来源
  • Python爬虫—常用的网络爬虫工具推荐
  • 英伟达与联发科合作生产支持G-SYNC完整功能的显示器 不需要英伟达专有模块
  • 【AI趋势9】开源普惠
  • GCB | 植物多样性影响生态系统多功能性对多种全球变化因子的响应
  • springboot系列教程(三十二):SpringBoot 教程之处理异步请求
  • 南京理工大学MOOC程序设计基础第5章测试答案解析
  • 大数据技术之Flume 拓扑结构(4)
  • 【18】逃逸分析
  • 电路笔记(PCB):数字滤波电路的拉普拉斯变换与零极点分析
  • TON链上游戏项目开发基本要求及模式创建与海外宣发策略
  • 【SQL】指定日期的产品价格
  • Linux进程间通信——硬件实现临界区互斥的基本方法
  • 机器学习的入门笔记(第十五周)
  • Git的使用教程及常用语法02
  • C++贪心算法