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>
  );
}
相关推荐
江拥羡橙1 小时前
Vue和React怎么选?全面比对
前端·vue.js·react.js
千码君20161 小时前
React Native:快速熟悉react 语法和企业级开发
javascript·react native·react.js·vite·hook
楼田莉子3 小时前
Qt开发学习——QtCreator深度介绍/程序运行/开发规范/对象树
开发语言·前端·c++·qt·学习
暮之沧蓝3 小时前
Vue总结
前端·javascript·vue.js
木易 士心4 小时前
Promise深度解析:前端异步编程的核心
前端·javascript
im_AMBER4 小时前
Web 开发 21
前端·学习
又是忙碌的一天4 小时前
前端学习day01
前端·学习·html
Joker Zxc4 小时前
【前端基础】20、CSS属性——transform、translate、transition
前端·css
excel4 小时前
深入解析 Vue 3 源码:computed 的底层实现原理
前端·javascript·vue.js
大前端helloworld4 小时前
前端梳理体系从常问问题去完善-框架篇(react生态)
前端