思路
React 与 Redux 异步状态操作的步骤:
1、创建store的写法保持不变,配置好同步修改状态的方法
2、单独封装一个函数,在函数内部return一个新函数,在新函数中
2.1、 封装异步请求获取数据
2.2、 调用同步actionCreater,传入异步数据,生成一个action对象,并使用dispatch提交
3、组件中dispatch的写法保持不变。
代码片段:
channelStore
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
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
store的入口文件