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

相关推荐
汉堡大王95273 分钟前
面试必考:手写代码 new 做了什么?从原理到实现全解析
前端·javascript·面试
BillKu27 分钟前
TypeScript中,字符串字面量联合类型(Union Type)、enum的用法说明
前端·javascript·typescript
jayson.h29 分钟前
PDF 合并+添加页码 相关库、类、函数
开发语言·前端·python
慧一居士2 小时前
Sass和Less功能、使用场景、用法对比
前端·css·less·sass
leoZ2312 小时前
AI+前端提效-09 AI赋能前端测试:单元测试、E2E测试自动生成,提升覆盖率
前端·人工智能·opencv·目标检测·数据挖掘·单元测试·语音识别
计算机魔术师2 小时前
OpenAI 评定 Astra 达到网络安全 Critical 能力阈值,将受限发布
前端
JavaGuide2 小时前
SpaceX 工程师的 AI Coding 玩法太牛了, 200 多个 Agent 并行!
前端·后端
小猪code2 小时前
frp 80/443 Web 服务两种部署模式实操笔记
前端·笔记
JamesZhang800782 小时前
Chrome相关知识点
前端
jayson.h3 小时前
python——pdf编辑
前端·python·pdf