理解 React / Redux / Relay 架构的区别

React 应用的架构

简单应用

简单的React应用,可以不使用任何架构,直接从state生成view

let state = initial
render(view(state), element)

state的变化,由setState方法或生命周期方法决定。

这种方法的缺点,主要是state的变化之间没有联系,难以追踪。

Redux架构

Redux架构由action来触发state变化,新的state必须在当前state的基础上生成。

let state = initial
let reduce = (state, action) => {}

function step(action){
// possible side effects //
state = reduce(state, action)
render(view(state), element)
}

// then call `step` on every `action`

只要给定当前stateaction,就能得到下一步的state,因此state的变化完全是有序可控的。

但是,Redux架构没对如何从数据源读写state做规定。

Relay 架构

Relay架构的核心思想是,state必须从数据源读取,即render(view(model.read(query)), element)

let read = (state, query, params) => {}
let mutate = (state, action) => {}

let model = { read, mutate }

// initial read/render
let state = model.read(view.query)
render(view(state), element)

function step(action){
if(action.type === 'setQuery'){
query = action.payload
step({ type: 'read' })
}
else if(action.type === 'read'){
state = merge(state, model.read(action.query || view.query))
}
else if(action.type === 'mutate') {
model.mutate(action)
if(action.query){
step({ type: 'read', query: action.query})
}
}
render(view(state), element)
}

上面代码中,model.read是远程读取,model.mutate是远程写入。query是GraphQL格式的查询语句,当前state实际上是写在query里面的。

来源:https://gist.github.com/threepointone/964ce9780a168a10e1bb

(完)

坚持原创技术分享,您的支持将鼓励我继续创作!