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

相关推荐
90后的晨仔5 小时前
从 H5 到 uni-app:一篇写给前端小白的"翻译指南"
前端·vue.js·前端框架
陈随易5 小时前
moon,apt和yum之外linux系统命令安装新选择
前端·后端·程序员
IT小盘6 小时前
13-企业Prompt模板-角色任务约束与输出格式
java·前端·prompt
徐小夕6 小时前
开源!我用SQLite + DuckDB打造了一款可视化AI问数平台
前端·算法·github
leslie1186 小时前
babel笔记
前端
用户059540174467 小时前
Redis 记忆存储踩坑实录:一个并发写入 Bug 让我排查了 4 小时
前端·css
小徐_23338 小时前
Wot UI 2.3.0 发布:二维码组件来了,Open Wot 与 wot-starter 同步更新
前端·微信小程序·uni-app
kyriewen8 小时前
Claude自己跑出去hack了3家公司——我为什么还在用它写代码
前端·ai编程·claude
IT_陈寒8 小时前
SpringBoot自动配置的坑,这次真踩疼我了
前端·人工智能·后端
子兮曰8 小时前
AI 浏览器 Agent 的安全困局:当自动化工具可以偷走你的登录态
前端·人工智能·后端