Redux 是一个用于管理 JavaScript 应用程序状态的库。它可以帮助你保持应用状态的可预测性和可维护性。
基本概念
- State: 状态是应用的数据。
- Action: 行为是描述如何改变状态的。
- Reducer: Reducer 是一个函数,它接受当前状态和动作,并返回新的状态。
安装
首先,你需要安装 Redux 和 React-Redux。
npm install redux react-redux
创建 Store
import { createStore } from 'redux';
const initialState = {
count: 0
};
const store = createStore(
reducer,
initialState
);
创建 Reducer
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 和 Redux
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import App from './App';
const store = createStore(reducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
Action Creator
function increment() {
return {
type: 'INCREMENT'
};
}
function decrement() {
return {
type: 'DECREMENT'
};
}
使用 Hooks
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(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
);
}
更多关于 Redux 的内容,请访问我们的Redux 教程。
图片
Redux 的核心概念之一是“不可变数据流”。下面是一个展示 Redux 状态的图片: