终于,我找到了问题所在。我被质疑的视图被放置在一个 .sheet 中。如果我单独显示此视图,环境变量将起作用,但如果将它们放在 .sheet 中,则必须显式注入 Store。
.sheet(isPresented: $showEditSheet){
EditFavoriteRootView().environmentObject(Store())
}
Run Code Online (Sandbox Code Playgroud)
现在它起作用了!
因为 ForEach 不能支持太复杂的逻辑,所以我在 View 中定义了一个函数来实现内容。在大多数情况下,这很好。但是,我不能在函数中使用EnviromentObject?
构建成功,视图主体中的按钮工作正常,但是当我单击函数中的按钮时出现运行时错误:
Fatal error: No ObservableObject of type Store found.
A View.environmentObject(_:) for Store may be missing as an ancestor of this view.: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/Monoceros/Monoceros-
Run Code Online (Sandbox Code Playgroud)
代码示例:
struct FromCategory: View {
@EnvironmentObject var store:Store
var body: some View {
ForEach(AppState.HealthCategoryList.keys.sorted(by: <),id:\.self){
self.ShowList(categoryId: $0)
}
Button(action:{
self.store.dispatch(.updateFavorite(idName:"test"))
}){Text("Test")}
}
func ShowList(categoryId:String)->some View{
let metalist = AppState.HealthCategoryList[categoryId]?.metaData?.sortedArray(using: [NSSortDescriptor(key: "idName", ascending: true)]) as! [HealthMetaData]
return VStack{
VStack(spacing:10) …Run Code Online (Sandbox Code Playgroud)