react redux异步请求

1,创建store

//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,导入子模块

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

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

export default store

3,使用

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>
  )
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值