简体   繁体   中英

Glimmer.js how to reset tracked property to initial value without using the constructor

In Glimmer.js, what is the best way to reset a tracked property to an initial value without using the constructor?

Note: Cannot use the constructor because it is only called once on initial page render and never called again on subsequent page clicks.

There are two parts to this answer, but the common theme between them is that they emphasize switching from an imperative style (explicitly setting values in a lifecycle hook) to a declarative style (using true one-way data flow and/or using decorators to clearly indicate where you're doing some kind of transformation of local state based on arguments).

  1. Are you sure you need to do that? A lot of times people think they do and they should actually just restructure their data flow. For example, much of the time in Ember Classic, people reached for a pattern of "forking" data using hooks like didInsertElement or didReceiveAttrs . In Glimmer components (whether in Ember Octane or in standalone Glimmer.js), it's idiomatic instead to simply manage your updates in the owner of the data: really doing data-down-actions-up.

  2. Occasionally, it does actually make sense to create local copies of tracked data in a component—for example, when you want to have a clean separation between data coming from your API and the way you handle data in a form (because user interfaces are API boundaries! ). In those scenarios, the @localCopy and @trackedReset decorators from tracked-toolbox are great solutions.

    • @localCopy does roughly what its name suggests. It creates a local copy of data passed in via arguments, which you can change locally via actions, but which also switches back to the argument if the argument value changes.

    • @trackedReset creates some local state which resets when an argument updates. Unlike @localCopy , the state is not a copy of the argument, it just needs to reset when the argument updates.

With either of these approaches, you end up with a much more “declarative” data flow than in the old Ember Classic approach: “forking” the data is done via decorators (approach 2), and much of the time you don't end up forking it at all because you just push the changes back up to the owner of the original data (1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM