You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.3 KiB

2 years ago
# 在响应式中谨慎使用解构
在刚接触编程的时候,我们就学过条件语句中断的特性,在Fix编程中,我们的computed计算属性有很多使用逻辑判断语句的.
**如果某个响应式属性与依赖某个state,那么在书写响应式属性取值函数时需要确保对响应式数据的获取在取值函数内发生.**
即`value = > get observe data and return`
结合一个实际场景举例:
demo代码如下,label的text属性采用响应式形式,min和max提前做了解构,那么当label点击触发修改状态之后,label的文本会随之改变吗?答案显而易见是不会的,因为违背了上面的原则,在text属性的计算函数外获取的state属性
```javascript
const Model = BI.inherit(Fix.Model, {
state: function () {
return {
max: 38,
min: 22,
};
},
actions: {
upup: function () {
this.model.max++;
this.model.min++;
},
},
});
BI.model("demo", Model);
const DemoWidget = BI.inherit(BI.Widget, {
_store: function () {
return BI.Models.getModel("demo");
},
render: function () {
const { min, max } = this.model;
return {
type: "bi.label",
height: 32,
text: () => `最高气温: ${max} 最低气温: ${min}`,
handler: () => {
this.store.upup();
},
};
},
});
BI.shortcut("demo_widget", DemoWidget);
const Demo = BI.createWidget({
type: "demo_widget",
});
```
调整方式也很容易,将state获取写入函数体内
```javascript
render: function () {
return {
type: "bi.label",
height: 32,
text: () => `最高气温: ${this.model.max} 最低气温: ${this.model.min}`,
handler: () => {
this.store.upup();
},
};
},
```
或者在函数体内解构,同样是在函数内部获取state属性
```javascript
render: function () {
return {
type: "bi.label",
height: 32,
text: () => {
const { min, max } = this.model;
return `最高气温: ${max} 最低气温: ${min}`;
},
handler: () => {
this.store.upup();
},
};
},
```