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')// 调用同步actioncreatedispatch(setChannels(res.data.data.channels))}
}export { fetchChannelList }const reducer = channelStore.reducerexport 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>)
}