学习react第三天

Redux

类似vuex和pinia

先安装对应包和插件

javascript 复制代码
npm install @reduxjs/toolkit react-redux

使用步骤

1.配置子模块

相关参数:createSlice(创建仓库),name,initialState,reducers,counterStore.actions,counterStore.reducer

javascript 复制代码
import { createSlice } from "@reduxjs/toolkit"

const counterStore = createSlice({
    // 名称
    name: "counterStore",
    // 初始状态数据
    initialState: {
        count: 0,   
    },
    // 修改数据方法
    reducers: {
        increment(state) {
            state.count += 1
        },
        decrement(state) {
            state.count -= 1
        }
    },
})

// 从counterStore中解构出counterCreater方法导出
export const { increment, decrement } = counterStore.actions
// 获取counterStore的reducer导出
const counterReducer = counterStore.reducer
export default counterReducer

2.导入根store组合

相关参数:configureStore(合并子仓库)

javascript 复制代码
import counterReducer from "./modules/counterStore";
import { configureStore } from "@reduxjs/toolkit";
import channelReducer from "./modules/channelStore";

const store = configureStore({
    reducer: {
        counterStore: counterReducer,
        channelStore: channelReducer,
    },
}); 

export default store;

3.在全局注册

相关参数:Provider

javascript 复制代码
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'
import store from './store/index.js'
import { Provider } from 'react-redux'


createRoot(document.getElementById('root')).render(
  <StrictMode>
    {/* 注入redux */}
    <Provider store={store}>
      <App />
    </Provider>
  </StrictMode>,
)

4.在组件中获取store中的数据和修改数据的方法

相关参数:useDispatch(获取dispatch), useSelector(获取对应store中的数据)

javascript 复制代码
import { useDispatch, useSelector } from 'react-redux'
import { increment, decrement } from '@/store/modules/counterStore.js'
import './App.css'

function App() {
  const { count } = useSelector(state => state.counterStore)
  const dispatch = useDispatch()
  return (
    <div className="App">
      <h1>Count: {count}</h1>
      <button onClick={() => dispatch(increment())}>count+</button>
      <button onClick={() => dispatch(decrement())}>count-</button>
    </div>
  )
}

export default App

5.传参方法

相关参数:action.payload

javascript 复制代码
addToNumber(state, action) {
     // action.payload 是传递过来的参数
     state.count += action.payload
}

6.异步传参

定义异步请求函数来dispatch reducers来修改数据

javascript 复制代码
// 异步请求
const getChannelList = () => {
    return async (dispatch) => {
        const res = await axios.get('http://geek.itheima.net/v1_0/channels')
        dispatch(setChannelList(res.data.data.channels))
    }
}

在组件页面调用的时候,要在useEffect钩子里面调用

javascript 复制代码
  useEffect(() => {
    dispatch(getChannelList())
  }, [dispatch])
相关推荐
小宋加油啊6 小时前
学习机械臂相关知识
学习
excel7 小时前
HLS TS 文件损坏的元凶:Git 提交与拉取
前端
Aphasia3117 小时前
https连接传输流程
前端·面试
徐小夕7 小时前
万字长文!千万级文档 RAG 知识库系统落地实践
前端·算法·github
threelab7 小时前
Three.js 物理模拟着色器 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
kyriewen7 小时前
CSS Container Queries:彻底告别 @media 写到手软,附 5 个真实布局案例
前端·css·面试
圣殿骑士-Khtangc8 小时前
单智能体落地实战:从 ReAct 到 Production-Ready AI Agent 全链路解析
人工智能·react.js
Patrick_Wilson9 小时前
router.replace 之后紧跟 reload,页面为什么无限刷新?
javascript·react.js·浏览器
小小小小宇9 小时前
OpenMemory MCP
前端
和平宇宙9 小时前
AI笔记005. hermes-DeepSeek V4 Pro, 128K上下文引发的探索
前端·人工智能·笔记