React.js 和 react-redux 的结合可以让你在 React 应用程序中有效地使用 Redux 进行状态管理。Redux 提供了一种集中管理应用程序状态的方法,而 react-redux 则提供了将这些状态与 React 组件关联起来的工具。

安装必要的依赖

首先,确保你已经安装了必要的依赖包:

npm install react-redux redux

如果你还打算使用 Redux 的中间件,例如 redux-thunk 来处理异步操作,也需要安装它:

npm install redux-thunk

创建 Redux Store

  1. 定义 Reducer:Reducer 是一个纯函数,它负责根据当前的状态和发送的动作(action)来计算新的状态。
// src/reducers/index.js
const initialState = {
  count: 0,
};

const counterReducer = (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;
  1. 创建 Store:Store 是 Redux 的核心概念之一,它持有整个应用的状态树。
// src/store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = createStore(
  rootReducer,
  applyMiddleware(thunk) // 如果需要中间件,这里添加
);

export default store;

使用 Provider 组件

为了使 React 组件能够访问 Redux store,你需要使用 react-reduxProvider 组件来包裹你的应用根组件。

// src/index.js
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')
);

使用 connectuseSelectoruseDispatch

connect 是一个高阶组件(HOC),它允许你将 Redux 的 dispatch 方法和一部分 Redux store 的状态注入到 React 组件中。对于函数组件,可以使用 useSelectoruseDispatch 钩子。

使用 connect
// src/components/Counter.js
import React from 'react';
import { connect } from 'react-redux';
import { increment, decrement } from '../actions';

const Counter = ({ count, onIncrement, onDecrement }) => (
  <div>
    <h1>Count: {count}</h1>
    <button onClick={onIncrement}>+</button>
    <button onClick={onDecrement}>-</button>
  </div>
);

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

const mapDispatchToProps = dispatch => ({
  onIncrement: () => dispatch(increment()),
  onDecrement: () => dispatch(decrement()),
});

export default connect(mapStateToProps, mapDispatchToProps)(Counter);
使用 useSelectoruseDispatch
// src/components/Counter.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from '../actions';

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

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => dispatch(increment())}>+</button>
      <button onClick={() => dispatch(decrement())}>-</button>
    </div>
  );
};

export default Counter;

创建 Action Creators

Action Creators 是生成 action 对象的函数。

// src/actions/index.js
export const increment = () => ({
  type: 'INCREMENT',
});

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

总结

通过上述步骤,你可以在 React 应用程序中有效地使用 Redux 来管理状态。react-redux 提供了两种主要的方式来将 Redux 的状态和操作与 React 组件结合起来:connectuseSelector / useDispatch。选择哪种方法取决于你的偏好和项目的需求。对于函数组件,推荐使用钩子,而对于类组件,则可以使用 connect