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 小时前
Ajax,vue生命周期(自动加载页面发出请求)Axios
前端·javascript·ajax
一点晖光2 小时前
ios底部按钮被挡住
前端·ios·微信小程序
cz追天之路8 小时前
华为机考--- 字符串最后一个单词的长度
javascript·css·华为·less
Light608 小时前
CSS逻辑革命:原生if()函数如何重塑我们的样式编写思维
前端·css·响应式设计·组件化开发·css if函数·声明式ui·现代css
蜡笔小嘟8 小时前
宝塔安装dify,更新最新版本--代码版
前端·ai编程·dify
ModyQyW9 小时前
HBuilderX 4.87 无法正常读取 macOS 环境配置的解决方案
前端·uni-app
bitbitDown9 小时前
我的2025年终总结
前端
五颜六色的黑10 小时前
vue3+elementPlus实现循环列表内容超出时展开收起功能
前端·javascript·vue.js
wscats10 小时前
Markdown 编辑器技术调研
前端·人工智能·markdown
EnoYao11 小时前
Markdown 编辑器技术调研
前端·javascript·人工智能