React - 使用Reducer实现全局状态管理

1、安装 @reduxjs/toolkit

yarn add @reduxjs/toolkit

安装 Redux 和相关库

yarn add redux react-redux @types/react-redux

使用 react-redux 库来将 Redux 连接到 React 应用程序中:

yarn add react-redux

2、在 src/store/index.ts 中创建 Redux store:

import { configureStore } from '@reduxjs/toolkit';
import rootReducer from './reducers';

const store = configureStore({
  reducer: rootReducer
});

export default store;

3、定义 Reducers分支:

src/store/reducers/counterReducer.ts 中定义 reducers,并添加相应的类型定义:

import { Reducer } from 'redux';

interface CounterState {
  count: number;
}

const initialState: CounterState = {
  count: 0
};

const counterReducer: Reducer<CounterState, any> = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'DECREMENT':
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
};

export default counterReducer;

4、合并 Reducers:

src/store/reducers/index.ts 中合并 reducers:

// 合并各个Reducer分支
import { combineReducers } from 'redux';
import { Reducer } from 'react';

import counterReducer from './counterReducer';

const rootReducer = combineReducers({
  counter: counterReducer,
  // Add other reducers here...
});

export default rootReducer;


5、连接 Redux 到 React:

src/index.tsx 中使用 <Provider> 提供 Redux store:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

6、在组件中使用 Redux 状态:

在您的 React 组件中使用 useSelectoruseDispatch 钩子来访问和更新 Redux 状态:

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';

const Counter = () => {
  const count = useSelector((state: RootState) => state.counter.count);
  const dispatch = useDispatch();

  const increment = () => {
    dispatch({ type: 'INCREMENT' });
  };

  const decrement = () => {
    dispatch({ type: 'DECREMENT' });
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
};

export default Counter;

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值