Redux 的使用可以概括为以下几个步骤:
- 安装 Redux 库
在项目中安装 Redux 库以便使用。可以使用 npm 命令来进行安装:
npm install redux
- 创建 Store 对象
使用 createStore() 函数创建 Store 对象。Store 本质上是一个 JavaScript 对象,它维护着整个应用程序的状态。创建 Store 对象需要传入一个 reducer 函数,它用于处理 action 对应的 state 更新操作。例如:
import { createStore } from 'redux';
const reducer = (state, action) => {
// 根据 action 的类型更新 state
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
default:
return state;
}
}
const initialState = { count: 0 };
const store = createStore(reducer, initialState);
- 定义 action
在 Redux 中通过 dispatch action 来触发特定的状态改变。可以使用 dispatch() 函数来分发 action 对象,该对象需要包含一个 type 属性,该属性是对 action 进行标识的字符串,例如:
store.dispatch({ type: 'INCREMENT' });
- 订阅 Store 的变化
使用 subscribe() 函数来订阅 Store 的变化,一旦 state 发生了变化,就会触发订阅函数,并且可以获得最新的 state 值。例如:
store.subscribe(() => {
const state = store.getState();
console.log(state.count);
});
- 关联组件和 Store
可以使用 React Redux 提供的 Provider 组件将整个应用程序的 Store 对象传递给组件,并使用 connect() 函数将 Redux 中的 state 和组件关联起来。例如:
import React from 'react';
import { Provider, connect } from 'react-redux';
const Counter = ({ count, dispatch }) => (
<div>
<h1>{count}</h1>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
</div>
);
const mapStateToProps = state => ({
count: state.count
});
const WrappedCounter = connect(mapStateToProps)(Counter);
const App = () => (
<Provider store={store}>
<WrappedCounter />
</Provider>
);