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 2024 (3)react中使用redux异步更新
2301_789169542024-10-09 10:34
相关推荐
还是大剑师兰特21 分钟前
什么是尾调用,使用尾调用有什么好处?m0_7482361130 分钟前
Calcite Web 项目常见问题解决方案Watermelo61742 分钟前
详解js柯里化原理及用法,探究柯里化在Redux Selector 的场景模拟、构建复杂的数据流管道、优化深度嵌套函数中的精妙应用m0_7482489444 分钟前
HTML5系列(11)-- Web 无障碍开发指南m0_748235611 小时前
从零开始学前端之HTML(三)一个处女座的程序猿O(∩_∩)O3 小时前
小型 Vue 项目,该不该用 Pinia 、Vuex呢?hackeroink6 小时前
【2024版】最新推荐好用的XSS漏洞扫描利用工具_xss扫描工具迷雾漫步者7 小时前
Flutter组件————FloatingActionButton向前看-8 小时前
验证码机制燃先生._.9 小时前
Day-03 Vue(生命周期、生命周期钩子八个函数、工程化开发和脚手架、组件化开发、根组件、局部注册和全局注册的步骤)