本文尝试解释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/