当前位置:首页 > React

react如何使用redux

2026-03-30 21:27:57React

安装 Redux 相关依赖

在 React 项目中安装 Redux 核心库和 React-Redux 绑定库:

npm install redux react-redux

如果需要异步操作(如 API 调用),还需安装中间件如 redux-thunk

npm install redux-thunk

创建 Redux Store

定义初始状态、Reducer 和 Store。Reducer 是一个纯函数,接收当前状态和 action,返回新状态。

react如何使用redux

// store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

// 初始状态
const initialState = {
  count: 0,
};

// Reducer
const rootReducer = (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;
  }
};

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

export default store;

使用 Provider 包裹应用

在根组件(如 App.js)中通过 Provider 提供 Store,使所有子组件可访问 Redux 状态。

// App.js
import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
import Counter from './Counter';

function App() {
  return (
    <Provider store={store}>
      <Counter />
    </Provider>
  );
}

export default App;

在组件中连接 Redux

使用 connect 或 Hooks(useSelectoruseDispatch)访问状态和派发 action。

react如何使用redux

方法 1:使用 connect(类组件)

// Counter.js
import React from 'react';
import { connect } from 'react-redux';

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

const mapStateToProps = (state) => ({
  count: state.count,
});

const mapDispatchToProps = (dispatch) => ({
  increment: () => dispatch({ type: 'INCREMENT' }),
  decrement: () => dispatch({ type: 'DECREMENT' }),
});

export default connect(mapStateToProps, mapDispatchToProps)(Counter);

方法 2:使用 Hooks(函数组件)

// Counter.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
    </div>
  );
}

export default Counter;

处理异步操作

使用 redux-thunk 派发异步 action,例如调用 API:

// actions.js
export const fetchData = () => {
  return async (dispatch) => {
    try {
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();
      dispatch({ type: 'SET_DATA', payload: data });
    } catch (error) {
      dispatch({ type: 'FETCH_ERROR', error });
    }
  };
};

// 在组件中调用
dispatch(fetchData());

组织代码结构

推荐按功能模块拆分 Redux 代码(Ducks 模式):

  • 将 action types、action creators 和 reducer 放在同一文件(如 counterSlice.js)。
  • 使用 combineReducers 合并多个 reducer(适用于大型应用)。
// counterSlice.js
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';

export const increment = () => ({ type: INCREMENT });
export const decrement = () => ({ type: DECREMENT });

const initialState = { count: 0 };

export default function reducer(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;
  }
}

分享给朋友:

相关文章

react native 如何

react native 如何

React Native 开发基础 React Native 是一个用于构建跨平台移动应用的框架,允许开发者使用 JavaScript 和 React 编写代码,同时生成原生 iOS 和 Androi…

电脑如何安装react

电脑如何安装react

安装 Node.js 和 npm React 依赖于 Node.js 和 npm(Node Package Manager)。从 Node.js 官网下载并安装最新稳定版本,安装完成后会自动包含 np…

react如何衰减

react如何衰减

React 中的动画衰减效果实现 在 React 中实现衰减效果(如滚动衰减、拖动释放后的惯性滑动)通常需要结合物理动画原理或第三方动画库。以下是几种常见方法: 使用 CSS 动画和 @keyfra…

react如何拓展

react如何拓展

React 拓展方法 使用高阶组件(HOC) 高阶组件是一种复用组件逻辑的方式,通过接收一个组件并返回一个新组件实现功能拓展。例如,为组件添加日志功能: function withLogging…

react如何检测

react如何检测

检测 React 应用的方法 使用 PropTypes 进行类型检查 PropTypes 是 React 内置的类型检查工具,用于验证组件的 props 是否符合预期。在开发环境中,PropTypes…

react如何调度

react如何调度

React 调度机制概述 React 的调度机制通过 Fiber 架构 和 Scheduler 模块实现任务优先级管理与时间切片(Time Slicing),确保高优先级更新(如用户交互)能快速响应,…