博主头像
<CodeEra />

心存敬畏 行有所止

React-Redux 基础运用学习笔记

React-Redux 是 React 和 Redux 之间的官方绑定库,它使得 React 组件能够方便地访问 Redux store 和派发 actions。

基本概念

1. Provider 组件

Provider 是一个高阶组件,它使 Redux store 对整个 React 应用可用。

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')
);

2. connect 函数

connect 函数用于连接 React 组件与 Redux store。

import { connect } from 'react-redux';

const MyComponent = ({ count, increment }) => (
  <div>
    <p>Count: {count}</p>
    <button onClick={increment}>Increment</button>
  </div>
);

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

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

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

现代用法:Hooks API

React-Redux 7.1+ 提供了 Hooks API,使得在函数组件中使用 Redux 更加简洁。

1. useSelector

从 Redux store 中选择和提取数据。

import { useSelector } from 'react-redux';

function Counter() {
  const count = useSelector(state => state.counter.count);
  
  return <div>Count: {count}</div>;
}

2. useDispatch

获取 dispatch 函数以派发 actions。

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

function Counter() {
  const count = useSelector(state => state.counter.count);
  const dispatch = useDispatch();
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>
        Increment
      </button>
    </div>
  );
}

完整示例

1. 创建 Redux Store

// store.js
import { createStore } from 'redux';

const initialState = {
  counter: { count: 0 }
};

function reducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, counter: { count: state.counter.count + 1 } };
    case 'DECREMENT':
      return { ...state, counter: { count: state.counter.count - 1 } };
    default:
      return state;
  }
}

const store = createStore(reducer);

export default store;

2. 创建 React 组件

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

function Counter() {
  const count = useSelector(state => state.counter.count);
  const dispatch = useDispatch();
  
  return (
    <div>
      <h2>Counter</h2>
      <p>Current count: {count}</p>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
    </div>
  );
}

export default Counter;

3. 应用入口

// 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}>
      <div className="App">
        <Counter />
      </div>
    </Provider>
  );
}

export default App;

最佳实践

  1. 使用 action creators - 创建函数来生成 action 对象
  2. 使用 Redux Toolkit - 简化 Redux 代码
  3. 按功能组织代码 - 使用 Ducks 模式或功能文件夹
  4. 避免过度使用 Redux - 只在需要全局状态时使用
  5. 使用 reselect - 用于创建记忆化的 selector 函数

Redux Toolkit 示例

现代 Redux 开发推荐使用 Redux Toolkit:

// counterSlice.js
import { createSlice } from '@reduxjs/toolkit';

export const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    increment: state => { state.value += 1 },
    decrement: state => { state.value -= 1 }
  }
});

export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;

然后在组件中使用:

import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './counterSlice';

function Counter() {
  const count = useSelector(state => state.counter.value);
  const dispatch = useDispatch();
  
  return (
    <div>
      <button onClick={() => dispatch(increment())}>+</button>
      <span>{count}</span>
      <button onClick={() => dispatch(decrement())}>-</button>
    </div>
  );
}

React-Redux 提供了简洁高效的方式来管理 React 应用中的全局状态,是现代 React 应用开发的重要工具之一。

发表新评论