Reast+Redux+Redux Toolkit+React Persist

原文链接:Redux+React

Redux

一、快速入门

Redux 是一个用于管理 JavaScript 应用程序状态的开源库。它广泛用于 React 应用程序中,但也可以与其他 JavaScript 框架一起使用,如Vue、Angular。Redux 旨在使状态管理更可预测、可维护和可扩展。

安装

npm install redux react-redux
yarn add redux react-redux

在 React 应用中,使用 Redux 通常是在以下场景下有益的:

  1. 共享状态:如果多个组件需要访问相同的状态数据,Redux 可以将这些状态中心化,以便在整个应用程序中共享和更新状态。
  2. 跨组件通信:当你需要在不同的组件之间传递数据或触发动作,Redux 提供了一种统一的方式来实现跨组件通信,而不需要通过多层嵌套传递 props。
  3. 持久化数据:如果你需要在应用程序刷新或导航时保留应用状态,Redux 可以与持久化库(如 Redux Persist)一起使用,以便在本地存储中保存状态数据。
  4. 中间件支持:Redux 支持中间件,这意味着你可以在处理动作时执行额外的逻辑,例如异步数据获取、日志记录、路由导航等。

Redux原理图

image-20231031205433415**

二、使用步骤

步骤 1: 安装 Redux

首先,你需要安装Redux和React-Redux。可以使用npm或者yarn:

# 使用 npm
npm install redux react-redux

# 使用 yarn
yarn add redux react-redux

步骤 2: 创建 Redux Store

在应用的主文件(index.js)中创建Redux store。Redux store是整个应用状态的容器。

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import rootReducer from './redux/reducers'; // 你的根 reducer

import App from './App';

const store = createStore(rootReducer); // 创建 store

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

步骤 3: 创建 Reducers

Reducers 定义了应用状态的修改方式。每个 reducer 函数都接收先前的状态和一个 action,返回新的状态。

// src/redux/reducers.js

import { combineReducers } from 'redux';
import countReducer from './countReducer'; // 你的 reducer

const rootReducer = combineReducers({
  count: countReducer, // 将所有的 reducer 放在这里
});

export default rootReducer;

步骤 4: 创建 Action Creators

Action creators 是用来创建 action 的函数。Action 是一个带有type属性的普通 JavaScript 对象,它描述了发生了什么。

// src/redux/actions.js

export const increment = (data) => ({ type:'INCREMENT' , data })

export const decrement = (data) => ({ type:'DECREMENT' , data })

步骤 5: 创建 Reducer 函数

Reducer 函数根据接收到的 action 的类型来更新应用的状态。

// countReducer.js

const countReducer = (preState = 0, action) => {
  const { type , data } = action
  switch (type ) {
    case 'INCREMENT':
      return preState + data;
    case 'DECREMENT':
      return preState - data;
    default:
      return state;
  }
};

export default countReducer;

步骤 6: 在 React 组件中使用 Redux

在 React 组件中,你可以使用connect函数连接组件与 Redux store。

// CountComponent

import React from 'react';
import {connect} from 'react-redux';
import {increment, decrement} from '../../redux/actions'; // 引入 action creators

const CountComponent = ({count, increment, decrement}) => {
    return (
        <div>
            <h1>Count: {count}</h1>
            <button onClick={() => increment(10)}>Increment</button>
            <button onClick={() => decrement(5)}>Decrement</button>
        </div>
    );
};

const mapStateToProps = (state) => {
    return {
        count: state.count, // 这里的 example 对应 rootReducer 中的 key
    };
};

export default connect(mapStateToProps, {increment, decrement})(CountComponent);

步骤 7: 在 React 类式组件中使用 Redux

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {increment, decrement} from '../redux/actions';

class Count extends Component {
    render() {
        return (
            <div>
                <h1>Count: {this.props.count}</h1>
                <button onClick={this.props.increment}>Increment</button>
                <button onClick={this.props.decrement}>Decrement</button>
            </div>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        count: state.count, // 这里的example对应rootReducer中的key
    };
};

export default connect(mapStateToProps, {increment, decrement})(Count);

三、异步Action

在React中使用Redux实现异步操作通常需要使用中间件,最常见的中间件是redux-thunkredux-thunk允许你在Redux action creators中返回函数而不仅仅是普通的action对象,这个函数可以进行异步操作。以下是在React中使用Redux实现异步操作的一般步骤:

步骤 1: 安装redux-thunk

首先,你需要安装redux-thunk中间件。

# 使用 npm
npm install redux-thunk

# 使用 yarn
yarn add redux-thunk

步骤 2: 配置Redux Store

在创建Redux store时,需要将redux-thunk中间件添加到store中。通常,你会在创建store的文件中配置中间件。

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './redux/reducers'; // 你的根 reducer

const store = createStore(rootReducer, applyMiddleware(thunk)); // 创建 store

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

步骤 3: 创建异步Action Creators

现在,你可以创建异步action creators。这些action creators返回一个函数,而不是一个简单的action对象。这个函数接收dispatch参数,允许你手动分派action。

// actions.js

import {
   INCREMENT, DECREMENT, ASYNC_DECREMENT} from "./action-type-const";

export const increment = data => ({
   type: INCREMENT, data})
export const 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值