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

相关推荐
前端小巷子2 分钟前
CSS 单位指南
前端·css
St2 分钟前
探索JavaScript原型链设计——详解prototype、__proto__及constructor三者之间的关系
前端·javascript
前端大白话3 分钟前
JavaScript中`Symbol.for()`和`Symbol()`的区别,在创建全局唯一的`Symbol`值时如何选择使用?
前端·javascript·设计模式
喵爱吃鱼3 分钟前
原来这就是react设计模式啊
前端·javascript·react.js
Synmbrf4 分钟前
说说平时开发注意事项
javascript·面试·代码规范
前端大白话5 分钟前
前端必看!90% 工程师踩过的状态管理坑,useReducer 如何一招化解?
前端·javascript·react.js
前端大白话5 分钟前
揭秘 HTML 可拖动元素及拖放功能:HTML5 API 大起底
前端·javascript·html
Moment22 分钟前
通过爬取 B 站热门视频来带你彻底了解 Playwright 🤷🏿‍♂️🤷🏿‍♂️🤷🏿‍♂️
前端·javascript·后端
Java~~38 分钟前
山东大学软件学院项目实训-基于大模型的模拟面试系统-前端美化滚动条问题
前端
掘金安东尼1 小时前
🧭 前端周刊第411期(2025年4月21日–27日)
前端·javascript·面试