通常我们使用 react 开发项目的时候,会把 redux 和 react-redux 库引进来,你是否思考过为什么需要 react-redux 库呢?今天就一起来分析一下这个问题。

Redux 本身是一个独立的库,可以与任何 UI 框架一起使用,包括 React,Angular,Vue,Ember 和 vanilla JS。尽管 Redux 和 React 经常一起使用,但它们彼此独立。

如果将 Redux 与任何类型的 UI 框架一起使用,通常将使用“UI 绑定”库将 Redux 与 UI 框架绑定在一起,而不是通过 UI 代码直接与 store 进行交互。

比如这样:

// 简单了解一下 redux 实现
function createStore(reducer) {
var state;
var listeners = []

function getState() {
return state
}

function subscribe(listener) {
listeners.push(listener)
return function unsubscribe() {
var index = listeners.indexOf(listener)
listeners.splice(index, 1)
}
}

function dispatch(action) {
state = reducer(state, action)
listeners.forEach(listener => listener())
}

dispatch({})

return { dispatch, subscribe, getState }
}
// 1) 创建 store
const store = createStore(counter)

// 2) subscription store 订阅更新,然后重新渲染 UI 界面
store.subscribe(render);

const valueEl = document.getElementById('value');

// 3. subscription callback runs 订阅回调执行:
function render() {
// 3.1) 获取当前 store state
const state = store.getState();

// 3.2) 提取所需数据
const newValue = state.toString();

// 3.3) 通过新的 state 去更新 UI 界面
valueEl.innerHTML = newValue;
}

// 4) 根据 store state 初始化 UI 界面
render();

// 5) Dispatch actions 派发
document.getElementById("increment")
.addEventListener('click', () => {
store.dispatch({type : "INCREMENT"});
})

对任何UI层使用Redux都需要相同的一致步骤:

  1. 创建 Redux store
  2. 订阅更新
  3. 在订阅回调中:1. 获取当前 store 状态 2. 提取此 UI 所需的数据 3. 用数据更新 UI
  4. 如有必要,使用初始状态呈现UI
  5. 通过 dispatch Redux actions 响应 UI 输入

尽管可以手动编写此逻辑,但这样做会变得非常重复。另外,优化 UI 性能将需要复杂的逻辑。

订阅存储,检查更新的数据以及触发重新渲染的过程可以变得更加通用和可复用。UI 绑定库(例如 React Redux)处理 store 交互逻辑,因此您不必自己编写该代码。