mobx 新增 isEmpty 裝飾器
阿新 • • 發佈:2018-12-03
避免 obj.xxx && obj.xxx.length 這樣的寫法
store
import * as u from "lodash"; function isEmpty(opt) { return function(target, key, des) { if (!opt) opt = `is${u.upperFirst(key)}`; Object.defineProperty(target, opt, { get: function proxyGetter() { return !u.isEmpty(this[key]); }, enumerable: true, configurable: true, }); }; } class IndexStore { @observable @isEmpty() lst = null; }
元件
@inject("indexStore") @observer class Test extends Component { componentDidMount() { setTimeout(() => { this.props.indexStore.lst = ["a", "b"]; }, 2000); setTimeout(() => { this.props.indexStore.lst = null; }, 4000); } render() { const { indexStore } = this.props; return ( <ul> {indexStore.isLst && indexStore.lst.map(el => <li key={el}>{el}</li>)} </ul> ); } }