马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
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>
- )
- }
复制代码 |