React Redux使用@reduxjs/toolkit的hooks

关于redux的学习过程需要几个官网,有redux官网,React Redux官网和Redux Toolkit的官网。

其中后者的中文没有找到,不过其中的使用在React Redux官网的快速入门中有介绍。

现在一般不使用connect借接口了。

对于借助Redux Toolkit的React Redux的应用示例可以看这个链接

https://blog.csdn.net/2202_75616310/article/details/134661399

注意:组件中使用state是从注册store的js的reducer里的key进行取用。useSelector((state) => state.counter2.value);这里的state是全局的state。

注册store的js

复制代码
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';

export default configureStore({
  reducer: {
    counter2: counterReducer,
  },
});

组件使用store的js

复制代码
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { decrement, increment } from './counterSlice';
import styles from './Counter.module.css';

export function Counter() {
  const count = useSelector((state) => state.counter2.value);
  const dispatch = useDispatch();

  return (
    <div>
      <div>
        <button
          aria-label="Increment value"
          onClick={() => dispatch(increment())}
        >
          Increment
        </button>
        <span>{count}</span>
        <button
          aria-label="Decrement value"
          onClick={() => dispatch(decrement())}
        >
          Decrement
        </button>
      </div>
    </div>
  );
}
相关推荐
@大迁世界7 小时前
Firefox 本地模式:localhost 再见了 ?
前端·架构
米米商聊9 小时前
同名附件为什么被 Map 覆盖?重复键与一对多索引
前端·javascript
echome88810 小时前
Python 异常处理:try、else、finally 的正确搭配
开发语言·前端·python·异常处理·编程技巧
时间的情敌10 小时前
OpenLayers 实战|Vue3 + OpenLayers 完整工程案例(加载天地图、要素、弹窗、绘制、WFS)
前端·openlayers
陈随易10 小时前
下载神器!Motrix 停更三年后重写回归
前端·后端·程序员
前端的日常11 小时前
一个人+AI做情侣食谱小程序,0 费用的服务器
前端·后端
计算机魔术师11 小时前
谷歌搜索广告踩刹车,AI广告成为救命稻草
前端
总要学点什么11 小时前
第81篇:数据可视化-PM2.5分布——让圆点的胖瘦替每座城市报出浓度
前端·信息可视化·echarts·cesium·空间分析
IT_陈寒11 小时前
Vue的v-for里用了个临时变量,页面直接挂了
前端·人工智能·后端
hunter_07611 小时前
一次 iOS 真机签名 409 的完整排查:证书、设备、描述文件为什么总是"对不上"
前端