本文嘗試解釋Redux是如何運做的。咱們將用Redux建立一個小案列。若是你正在找靠譜的Redux文檔,能夠去看官方文檔。html
來自官方文檔的描述:Redux是一個可預測的JavaScript狀態容器。換句話說,Redux就是用來處理和管理應用的狀態/數據。react
以下:git
更多圖解 點這裏_github
如今咱們來一步一步來解答上面的圖表明什麼意思。web
任何應用都有一個狀態。有些狀態保存在數據庫中,有些狀態保存到不一樣的地方。在Redux中,狀態存在一個單一的對象中。它知道哪一個頁面正打開着,它知道當前用戶信息等等。狀態多是標準化,也能夠是規範化的,因此當在不一樣的瀏覽器打開時,會渲染出相同的應用(一樣的頁面,一樣的用戶...)數據庫
讓咱們爲計數應用定義咱們的狀態:redux
`var initialState = {counter: 0}`
複製代碼
Redux和React.js一塊兒用效果很好,可是不用react.js也能夠。咱們用原生JavaScript來把狀態渲染到頁面:瀏覽器
`<div>-</div>`
複製代碼
function render(state) {
document.getElementById('counter').textContent = state.counter;
}
複製代碼
若是應用狀態發生改變,那是由於有Actions觸發了。他們多是用戶操做,也多是異步操做,定時操做扥等等。咱們將定義一個按鈕來觸發操做。bash
`<button id="button">Increment</button>`
複製代碼
`document.getElementById('button').addEventListener('click', incrementCounter)`
複製代碼
Actions不會立刻改變state。Redux的 store 處理這事:服務器
var store = Redux.createStore(reducer, initialState)
function incrementCounter() {
store.dispatch({
type: 'INCREMENT'
})
}
複製代碼
store保存當前的狀態,以及對actions作出反應。當一個action被觸發,傳入當前的state和當前的action到reducer中,reducer返回新的state,state被更新:
function reducer(state, action) {
if (action.type === 'INCREMENT') {
state = Object.assign({}, state, {counter: state.counter + 1})
}
return state
}
複製代碼
當state改變,從新渲染:
store.subscribe(function() {
render(store.getState())
})
複製代碼
一個React.js渲染器能夠很好的處理這件事,只更新改變的部分,而不會去更新所有。
若是action沒有被觸發就不會渲染,因此咱們來觸發第一次渲染:
`render(store.getState())`
複製代碼
// html
<div>-</div>
<button id="button">Inc</button>
複製代碼
// js
var initialState = {counter: 0}
var store = Redux.createStore(reducer, initialState)
function render(state) {
document.getElementById('counter').textContent = state.counter;
}
document.getElementById('button').addEventListener('click', function() {
incrementCounter()
})
function incrementCounter() {
store.dispatch({
type: 'INCREMENT'
})
}
function reducer(state, action) {
if (action.type === 'INCREMENT') {
state = Object.assign({}, state, {counter: state.counter + 1})
}
return state
}
store.subscribe(function() {
render(store.getState())
})
// 渲染初始化的 state
render(store.getState())
複製代碼
在Redux中,你能夠控制任何事:actions, action的建立,狀態更新等等。意味着每一個應用程序都是能夠預測的。可是致使了不少重複的代碼。另外一方面,MobX達到相同的效果,但隱藏了一些用戶觸發的actions,因此你能夠寫更少的代碼。
固然,Redux更加成熟,以及支持一些新特性,好比服務器端渲染和一些很棒的開發工具。
原文:https://bumbu.github.io/simple-redux/