Immut-Store
写在前面
- 如果在
写业务代码
(当然不是框架啦) 中觉得 flux
redux
reflux
都太复杂, 不妨试试这个
使用
1. 定义store
import {ImmutStore} from 'immut-store'
class User extends ImmutStore {
constructor(name = '') {
super()
this._name = name
this._version = 0
}
updateName(name) {
if (name !== this._name) {
this._name = name
this._version ++
this.emitChange()
}
}
hashCode() {
return this._version
}
}
import {ImmutStore} from 'immut-store'
import Immutable from 'immutable'
class User extends ImmutStore {
constructor(name = '') {
super()
this._data = new Immutable.fromJS({name: name})
}
updateName(name) {
this._data = this._data.set('name', name)
this.emitChange()
}
hashCode() {
return this._data.hashCode()
}
}
- ps: 有些时候并不需要刻意使用immutable, 比如我们很容易人肉判断数据是否变化的, 这时候可以用第一种方式了.
2. 绑定store到react 顶层节点
import {bind} from 'immut-store'
import React, {Component} from 'react'
import user from './user'
import story from './story'
@bind(user, story)
class App extends Component {
constructor(props) {
super(...arguments)
}
render() {
return <div>
<UserInfo user={user} />
<Story story={story} />
</div>
}
}
- ps: 这里的绑定是通过判断user和story数据的hashCode变化, 如果任意一个有变化就会触发App的render
3. 子层节点使用need传递immutable数据
import {need} from 'immut-store'
import React, {Component} from 'react'
@need('user')
class UserInfo extends Component {
constructor(props) {
super(...arguments)
}
render() {
return <div>{this.props.user.name}</div>
}
}
- ps: 这里同样是判断user的hashCode变化来触发render, 不同的是user数据必须是从父节点分发下来的
最后
- 想了解多点, 直接看代码把, 因为,
真的很少!!