[英]Ember Octane - Display contents of a Tracked Array from Controller in Template?
[英]Ember Octane, Tracked property not rerendering template
來自 React 背景,我在理解 EmberJs“Tracked”概念時遇到了問題。 在紙面上它不應該與“反應狀態”不同。
所以我的理解是,當我們用@tracked
注釋一個屬性時,當這個屬性發生變化時,它應該會導致重新渲染。
請看下面的代碼:
ProductItem組件
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
export default class ProductItemIndexComponent extends Component {
@service('cart') cartService;
@tracked addedToCart = false;
@action
checkItemInCart(id) {
if (this.cartService.items.findBy('id', id)) {
this.addedToCart = true;
} else {
this.addedToCart = false;
}
}
}
模板,
<div class="card-container">
<div class="card product-item" {{did-insert (fn this.checkItemInCart @item.id)}}>
<img src={{@item.image}} class="product-image card-img-top" alt="...">
<div class="card-body">
<h5>{{@item.title}}</h5>
</div>
<div class="footer">
<p class="card-text"><span class="badge badge-secondary"><strong>Price: </strong>{{@item.price}}</span></p>
<button type="button" class="btn btn-warning" {{on 'click' (fn @handleCartAction item)}}
disabled={{this.addedToCart}}>Add
to cart</button>
</div>
</div>
</div>
當我第一次渲染組件時,我使用{{did-insert (fn this.checkItemInCart @item.id)}}
檢查購物車中是否存在當前商品,如果存在,我將切換跟蹤屬性@tracked addedToCart = false;
為真否則為假。
從理論上講,這應該在我的 productItem 模板中一找到cartService
中的 Item 就禁用我的按鈕。 它僅在我 go 到另一個頁面然后返回時才有效。
但是頁面沒有重新呈現。 有人可以幫助我了解我可能做錯了什么嗎?
先感謝您
您的問題是checkItemInCart
只被調用一次,因此一旦更改cartService.items
addedToCart
就不會更新。
我認為正確的解決方案是使addedToCart
依賴於cartService.items
和item
get addedToCart(){
return !!this.cartService.items.findBy('id', this.args.item.id)
}
為此, cartService.items
也應該是 tracked 屬性,並使用pushObject
等方法進行更新,請參閱為什么我的跟蹤數組不會在 Ember Octane 中更新?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.