@State 的限制 [英] Limitation Of @State

查看:26
本文介绍了@State 的限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一些文章中看到@state有很多限制

I saw in some article that @state has many limitations

  • 我们不应该将它与复杂的模型一起使用,最好将它与简单的属性一起使用,例如 string、bool 等.
  • 我们应该在视图内部使用它.

我尝试创建一个结构模型并在 contentview (ParentView) 中用 @state 标记它,并通过用 @binding 包装它来将此模型传递给它的子视图,它工作得很好,所以我不明白为什么我们仍然需要@objectbinding,因为我们可以将相同的值传递给这些子视图,如果一个改变其他也会改变?或者@objectbinding 解决的@state 的局限性是什么?

I tried to make a struct model and mark it with @state in the contentview (ParentView) and pass this model to its child views by wrapping it with @binding it worked just fine, so i don't understand why we still need @objectbinding as we can pass the same value to these child views and if one change the others will change also? or what are the limitations of @state that @objectbinding solve?

推荐答案

我建议您观看 WWDC 2019 会议:SwiftUI 中的数据流.这是很好的解释.它描述了在哪些情况下 @State 是完全可以接受的,而在哪些情况下需要 ObjectBinding/EnvironmentObject.会议只有 37 分钟长,但它将是您对绑定理解的前后对比.请务必观看,从长远来看会节省时间.

I recommend you watch WWDC 2019 session: Data Flow in SwiftUI. It is very well explained. It describes in which scenarios @State is perfectly acceptable and where ObjectBinding/EnvironmentObject is necessary instead. The session is only 37 minutes long, but it will be a before and after in your understanding of bindings. Please do watch it, it will save time in the long run.

这一切都归结为了解数据的真实来源"在哪里.这个概念也在视频中进行了解释.简而言之,事实的来源是您的数据的诞生.如果您的变量的数据可以从某个其他变量导出,那么它不是真实来源.

It all comes down to understanding where is the "source of truth" of your data. This is a concept that is also explained in the video. In a few words, the source of truth is were your data is born. If the data of your variable can be derived from some other variable, then it is not a source of truth.

@State@BindableObject 有什么区别?

@State:它是视图本地的.它必须是值类型(例如,struct、Int、String、Array 等)并且其存储由框架管理.

@State: It is local to the view. It has to be a value-type (e.g., a struct, Int, String, Array, etc) and its storage is managed by the framework.

@BindableObject:它在视图外部,它是一个引用值(例如,一个类)并且它的存储由你管理,给你更大的灵活性实现你自己的逻辑.

@BindableObject: It is external to the view, it is a reference value (e.g., a class) and its storage is managed by you, giving you more flexibility to implement your own logic.

请注意,@State 变量在为您的应用程序设计原型时也非常有用.例如,如果您正在处理视图的布局,您最初可以使用 @State 变量来简化操作.一旦您的视图完成您想要的操作,您就可以专注于创建您的 @BindableObject 并替换您的 @State.

Note that @State variables are also great while prototyping your app. For example, if you are working on the layout of your view, you can initially use a @State variable to make things easier. Once your view does what you want, you can concentrate on creating your @BindableObject and replace your @State.

这篇关于@State 的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆