react redux异步请求

1,创建store

javascript 复制代码
//store/modules/channelStore.js
import { createSlice } from "@reduxjs/toolkit"
import axios from "axios"

const channelStore = createSlice({
  name: 'channel',
  initialState: {
    channelList: []
  },
  reducers: {
    setChannels (state, action) {
      state.channelList = action.payload
    }
  }
})

// 异步请求部分
const { setChannels } = channelStore.actions
// 单独封装一个函数 在函数内部return一个新函数
const fetchChannelList = () => {
  return async (dispatch) => {
    // 调用异步请求
    const res = await axios.get('http://geek.itheima.net/v1_0/channels')
    // 调用同步actioncreate
    dispatch(setChannels(res.data.data.channels))
  }
}

export { fetchChannelList }

const reducer = channelStore.reducer

export default reducer

2,导入子模块

javascript 复制代码
// store/index.js
import { configureStore } from "@reduxjs/toolkit"
// 导入子模块reducer
import channelReducer from "./modules/channelStore"

const store = configureStore({
  reducer: {
    channel: channelReducer
  }
})

export default store

3,使用

javascript 复制代码
import { fetchChannelList } from "./store/modules/channelStore"
import { useEffect } from "react"

function App () {
  const { channelList } = useSelector(state => state.channel)
  // 得到dispatch函数
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(fetchChannelList())
  }, [dispatch])
  
  return (
    <div className="App">
      <ul>
        {channelList.map(item => <li key={item.id}>{item.name}</li>)}
      </ul>
    </div>
  )
}
相关推荐
懒大王952715 分钟前
uni-app + Vue3 + EZUIKit.js 播放视频流
开发语言·javascript·uni-app
懒大王952719 分钟前
uni-app + Vue3 开发展示 echarts 图表
前端·uni-app·echarts
yinuo26 分钟前
Uni-App跨端实战:微信小程序WebView与H5通信全流程解析(01)
前端
xkroy44 分钟前
ajax
前端·javascript·ajax
Yvonne爱编码1 小时前
AJAX入门-URL、参数查询、案例查询
前端·javascript·ajax
闲人编程1 小时前
前端形态与样式风格:从古典到现代的视觉语言演进
前端·css·状态模式·组件·js·风格·响应式
JudithHuang1 小时前
Mac版微信开发者工具登录二维码不显示问题解决方案
前端
Swift社区1 小时前
如何解决 Vue2 前端项目为何无法访问本地资源(chunk.js 加载一直 pending/转圈)
开发语言·前端·javascript
清风细雨_林木木2 小时前
Vue加载资源‘如图片’的“直接引入“方式和“request()“的区别
前端·javascript·vue.js