Redux 基本概念
- Redux 是一个流行的状态管理库,使用单一状态树来管理整个应用的状态;
- 前面存储变量的对象,给他一个确切的定义——状态仓库 (store),不同于对象操作的是:任何时候你都不能直接去更改状态仓库 (store) 中的值,而是需要使用纯函数进行状态修改;
什么是纯函数?如果函数的调用参数相同,则永远返回相同的结果;它不依赖于程序执行期间函数外部任何状态或数据的变化,必须只依赖于其输入参数;该函数不会产生任何可观察的副作用;
Redux 原理
-
Redux 的核心概念包括:
单一数据源
:整个应用的状态存储在一个对象树中,这个对象树仅存在于一个 store 中;状态是只读的
:唯一改变状态的方法是触发 action,action 是一个描述发生什么的对象;使用纯函数来执行修改
:为了描述 action 如何改变状态树,需要编写 reducers;
-
Redux 的 store 是由 createStore 创建的,它包含以下几个方法:
getState
:获取当前状态;dispatch
:触发 action;subscribe
:添加监听器;replaceReducer
:替换当前 reducer;
Redux 基本使用
示例代码
-
安装 Redux 和 React-Redux
npm install redux react-redux
-
创建 Action
// actions.js export const increment = () => ({ type: 'INCREMENT' }); export const decrement = () => ({ type: 'DECREMENT' });
-
创建 Reducer
// reducer.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;
-
创建 Store
// store.js import { createStore } from 'redux'; import counterReducer from './reducer'; const store = createStore(counterReducer); export default store;
-
使用 Provider 提供 Store
// 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') );
-
连接组件
// Counter.js import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { increment, decrement } from './actions'; const Counter = () => { const count = useSelector((state) => state.count); // 从 store 中提取特定数据的函数 const dispatch = useDispatch(); // 发送 action 的方法 return ( <div> <h1>{count}</h1> <button onClick={() => dispatch(increment())}>Increment</button> <button onClick={() => dispatch(decrement())}>Decrement</button> </div> ); }; export default Counter;
Redux 流程图
-
全局通常只有一个 Store 存储 State;
-
Component 中在某些情况会派发 Action (这些 Action 是提前定义好的);
-
Reducer 会接收到这些 Action,并且在 Reducer 中会返回一个新的 State,作为 Store 的 State;
-
State 发生更新之后会触发通知,告知订阅者数据发生了改变;
-
订阅者拿到最新的数据 (在 props 中),更新到 jsx 中,界面发生改变;
React✍️ React 基础语法
上一篇