redux 2024 (3)react中使用redux异步更新

复制代码
import { createSlice } from "@reduxjs/toolkit";

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

// 异步请求
const {setChannels} = channelStore.actions
const fetchChannelList = ()=>{
    return async(dispatch)=>{
      const res = await axios.get('http://geek.itheima.net/v1_0/channels')
      dispatch(setChannels(res.data.data.channels))
    }
}

export {fetchChannelList}

const reducer = channelStore.reducer

export default reducer

import { configureStore } from "@reduxjs/toolkit"; //configureStore 接受一个名为 reducer 的函数作为命名参数;configureStore 会自动使用良好的默认设置来设置 store
import counterReducer from './modules/counterStore'
import channelReducer from './modules/channelStore'
const store = configureStore({
    reducer:{
        counter:counterReducer,
        channel:channelReducer
    }
})
export default store

import {useDispatch,useSelector } from "react-redux";
import {increment,decrement,addToNum} from './store/modules/counterStore'
import { fetchChannelList } from "./store/modules/channelStore";
import { useEffect } from "react";
function App() {
  const {count} = useSelector(state =>state.counter)//获得state的数据
  const {channelList} = useSelector(state =>state.channel)
  const dispatch = useDispatch()

  // 使用useEffect触发异步请求
  useEffect(()=>{
    dispatch(fetchChannelList())
  },[dispatch])
  return (
    <>
    <button onClick={()=>dispatch(decrement())}>-</button>
{count}
<button onClick={()=>dispatch(increment())}>+</button>
<button onClick={()=>dispatch(addToNum(10))}>Add to 10</button>
<button onClick={()=>dispatch(addToNum(20))}>Add to 20</button>

<ul>
 {channelList.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
    </>
  )
}

export default App

黑马前端Redux快速入门到美团实战教程,前端React集中状态管理工具redux视频教程_哔哩哔哩_bilibili

相关推荐
铁皮饭盒1 分钟前
Bun 处理 IO 密集型比 Java 强多少?
javascript
anod3 分钟前
Amazon反爬虫:一场从自动化到Chrome插件的折腾之旅
javascript·chrome·amazon·插件
葡萄城技术团队9 分钟前
AI 不会淘汰电子表格,反而会让电子表格成为 AI 操作系统
前端·人工智能
BigTopOne9 分钟前
Short Put and Short Call
前端
Cache技术分享21 分钟前
465. Java 反射 - 获取类的简单名
前端·后端
BigTopOne29 分钟前
什么是行权价,什么是权利金,什么是行权?
前端
xlxxy_31 分钟前
sap获取批次特性报表
java·linux·开发语言·前端·数据库·abap·mm
BigTopOne32 分钟前
Long put and Long call
前端
石像鬼₧魂石41 分钟前
【Y2Ksoft】贵阳陈桥饭店ERP管理系统
大数据·前端·物联网·html·数据库架构
TheITSea1 小时前
4、React+Tailwind CSS
前端·css·react.js