当前位置:首页 > 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,返回新状态。

// 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。

方法 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 模式):

react如何使用redux

  • 将 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页面

如何react页面

创建 React 页面 使用 create-react-app 快速初始化项目: npx create-react-app my-app cd my-app npm start 基础页面结构 在 s…

react如何运行

react如何运行

运行React项目的步骤 安装Node.js 确保系统已安装Node.js(建议版本12以上),可从官网下载并安装。Node.js自带npm包管理器,用于后续依赖安装。 创建React项目 使用官方…

react如何encode

react如何encode

React 中编码的实现方式 在 React 中,编码通常涉及对 URL、HTML 实体或特殊字符的处理。以下是几种常见的编码方法: 使用 encodeURIComponent 进行 URL 编码…

如何运行react

如何运行react

运行 React 项目的步骤 安装 Node.js 和 npm 确保系统已安装 Node.js(包含 npm)。可通过官网 Node.js 下载并安装最新稳定版本。安装完成后,验证版本: node…

react如何刷新

react如何刷新

刷新React组件的方法 使用状态更新触发重新渲染 通过更新组件的状态可以触发重新渲染。React会在状态变化时自动重新渲染组件。 const [count, setCount] = useStat…

react如何清理

react如何清理

清理 React 项目的方法 清理未使用的依赖项 运行 npm prune 或 yarn install --production 可以移除 node_modules 中未在 package.json…