React Redux 是一个用于在 React 应用程序中管理状态的库。它结合了 React 和 Redux,使得状态管理更加简单和可预测。
安装 Redux 和 React-Redux
首先,你需要安装 Redux 和 React-Redux。你可以使用 npm 或 yarn 来安装:
npm install redux react-redux
# 或者
yarn add redux react-redux
创建 Store
在 Redux 中,所有的状态都存储在一个单一的 store 对象中。你可以使用 createStore
函数来创建一个 store:
import { createStore } from 'redux';
const store = createStore(reducer);
创建 Reducer
Reducer 是一个纯函数,它接受当前的 state 和一个 action,然后返回一个新的 state。这里有一个简单的例子:
const initialState = {
count: 0
};
function 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;
}
}
连接 React 组件
使用 Provider
组件来将 Redux store 连接到 React 组件树:
import { Provider } from 'react-redux';
import store from './store';
function App() {
return (
<div>
<Counter />
</div>
);
}
const WrappedApp = () => (
<Provider store={store}>
<App />
</Provider>
);
export default WrappedApp;
使用 Connect 连接组件
你可以使用 connect
高阶组件来将 Redux state 和 dispatch 方法连接到 React 组件:
import { connect } from 'react-redux';
const Counter = ({ count, increment, decrement }) => (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={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);
更多资源
想要了解更多关于 React Redux 的信息,可以访问我们的 React Redux 教程。
想要学习更多关于 React 的知识,可以查看我们的 React 教程。