避免 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>
);
}
}