Redux与React5

项目准备:

在React中使用redux,官方要求安装俩个其他插件 - Redux Toolkit 和 react-redux

1. Redux Toolkit(RTK)- 官方推荐编写Redux逻辑的方式,是一套工具的集合集,简化书写方式

2. react-redux - 用来 链接 Redux 和 React组件 的中间件

1. 使用 CRA 快速创建 React 项目 npx create-react-app react-redux

2. 安装配套工具 npm i @reduxjs/toolkit react-redux

3. 启动项目 npm run start

store目录结构设计

1. 通常集中状态管理的部分都会单独创建一个单独的 `store` 目录

2. 应用通常会有很多个子store模块,所以创建一个 `modules` 目录,在内部编写业务分类的子store

3. store中的入口文件 index.js 的作用是组合modules中所有的子模块,并导出store

实现counter:

import { createSlice } from "@reduxjs/toolkit";
const counterStore=createSlice({
    name:'counter',
    initialState:{
        count:0
    },
    //修改数据的方法--同步方法,直接修改

    reducers:{
        instrement(state){
            state.count++
        }
    },
    decrement(state){
        state.count--
    }
})
//解构出来actionCreater函数
const {instrement,decrement} = counterStore.actions
//获取reducer
 const reducer = counterStore.reducer

 //以按需导出的防守导出actionCreater

export {instrement,decrement}
 //以默认导出的方式导出reducer
 export default reducer
//入口
//子模块导出reducer
import counterReducer from './modules/counterStore'
import { configureStore } from "@reduxjs/toolkit";
const store=configureStore({
    reducer:{
        counter:counterReducer
    }
})
export default store 

为React注入store react-redux负责把Redux和React 链接 起来,内置 Provider组件 通过 store 参数把创建好的store实例注入到应用中 ,链接正式建立

React组件使用store中的数据 在React组件中使用store中的数据,需要用到一个 钩子函数 - useSelector,它的作用是把store中的数据映射到组件 中,使用样例如下:

React组件修改store中的数据 React组件中修改store中的数据需要借助另外一个hook函数 - useDispatch,它的作用是生成提交action对象的 dispatch函数,使用样例如下:

1. 组件中使用哪个hook函数获取store中的数据?

useSelector

2. 组件中使用哪个hook函数获取dispatch方法?

useDispatch

3. 如何得到要提交action对象?

执行store模块中导出的actionCreater方法

redux与React - 提交action传参

组件中有俩个按钮 `add to 10` 和 `add to 20` 可以直接把count值修改到对应的数字,目标count值是在组件中传递过 去的,需要在提交action的时候传递参数

实现需求:在reducers的同步修改方法中添加action对象参数,在调用actionCreater的时候传递参数,参数会被传递到action对 象payload属性上

注意:这里的参数会自动到payload的count中

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值