二、Redux 快速入门

126 阅读1分钟

什么是 Redux

image.png

image.png

快速入门

image.png

image.png

image.png

image.png

readux 和 react

环境准备

Redux Toolkit & react-redux

image.png

image.png

code

image.png

案例

image.png

使用 react toolkit 创建 counterStore

image.png

为 react 注入 store

image.png

React组件使用 store 中的数据

image.png

image.png

React 修改 store 中的数据

image.png

提交 action 传参需求

image.png

异步操作

image.png

import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'

const channelStore = createSlice({
  name: 'channel',
  initialState: {
    channelList: []
  },
  reducers: {
    setChannelList (state, action) {
      state.channelList = action.payload
    }
  }
})


// 创建异步
const { setChannelList } = channelStore.actions
const url = 'http://geek.itheima.net/v1_0/channels'
// 封装一个函数 在函数中return一个新函数 在新函数中封装异步
// 得到数据之后通过dispatch函数 触发修改
const fetchChannelList = () => {
  return async (dispatch) => {
    const res = await axios.get(url)
    dispatch(setChannelList(res.data.data.channels))
  }
}

export { fetchChannelList }

const channelReducer = channelStore.reducer
export default channelReducer

React 调试

Redux DevTools React Developer Tools

参考

www.yuque.com/fechaichai/…