【React】react-redux 异步状态操作

异步状态操作

异步操作步骤

  • 创建store的写法保持不变,配置好同步修改状态的方法
  • 单独封装一个函数,在函数内部return一个新函数,在新函数中
    • 封装异步请求获取数据
    • 调用同步actionCreater传入异步数据生成一个action对象,并使用dispatch提交
  • 组件中dispatch的写法保持不变

异步实现示例

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

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/index.js

import { configureStore } from "@reduxjs/toolkit"
// 导入子模块reducer
import counterReducer from "./modules/counterStore"
import channelReducer from './modules/channelStore'

// 创建store组合子模块
const store = configureStore({
    reducer: {
        counter: counterReducer,
        channel: channelReducer
    }
})

export default store

App.js

import { useSelector, useDispatch } from 'react-redux'

// 导入actionCreater
import { increment, decrement, AddToNum } from "./store/modules/counterStore";
import { fetchChannelList } from './store/modules/channelStore'
import { useEffect } from 'react';

function App() {
  const { count } = useSelector(state => state.counter)
  const { channelList } = useSelector(state => state.channel)
  const dispatch = useDispatch()

  // 使用 useEffect 触发异步请求执行
  useEffect(() => {
    dispatch(fetchChannelList())
  }, [dispatch])

  // 模板渲染
  return (
    <div className="App">
      <button onClick={() => dispatch(decrement())}>-</button>
      {count}
      <button onClick={() => dispatch(increment())}>+</button>
      <button onClick={() => dispatch(AddToNum(10))}>+10</button>
      <button onClick={() => dispatch(AddToNum(20))}>+20</button>
      <ul>
        {channelList.map(item => <li key={item.id}>{item.name}</li>)}
      </ul>
    </div>
  );
}

export default App;

posted @ 2024-09-18 17:38  505donkey  阅读(64)  评论(0)    收藏  举报