[英]Uncaught Error with Webassembly using Yew Framwork
我正在使用 Yew 編寫一個主題切換器,通過單擊循環切換不同的主題。 這是我的更新功能。 它獲取存儲在共享狀態中的當前主題,這取決於 theme_cycle 中接下來會發生什么,共享狀態中的主題值被設置為它。
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::ChangeTheme => {
let theme_cycle: [&str; 3] = ["light", "dark", "rust"];
let current_theme = self.props.handle.state().theme.clone();
// eval next theme
let next_theme = match theme_cycle.iter().position(|x| x == ¤t_theme) {
None => theme_cycle[0].to_string(),
Some(i) => {
if i >= (current_theme.len() - 1) {
theme_cycle[0].to_string()
} else {
theme_cycle[i + 1].to_string()
}
},
};
// set next theme
self.props.handle.reduce(move |state| state.theme = next_theme.clone());
// store it inside localstorage
},
Msg::ToggleLangDropdown => self.show_dropdown = !self.show_dropdown,
};
true
}
但是,如果共享狀態中的主題 val 為“rust”,並且我再次單擊調用 Msg::ChangeTheme 的按鈕,則該主題應設置為“light”,但我的代碼會出現混亂,並且在里面出現“Uncaught Error: undefined”瀏覽器控制台。
我找到了一種解決方法; 我沒有使用數組並訪問值,而是嘗試執行相同的任務,但僅使用迭代器,並確保更新函數不擁有函數本身之外的任何變量的所有權(我真的不知道這是否是不過真的很有必要……)
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::ChangeTheme => {
let theme_cycle = ["light".to_string(), "dark".to_string(), "rust".to_string()];
let current_theme = self.props.handle.state().theme.clone();
let indexof_current_theme = match theme_cycle.iter().position(|x| x.to_string() == current_theme) {
None => 0,
Some(x) => x.clone(),
};
let next_theme = match theme_cycle.iter().nth(indexof_current_theme + 1) {
None => theme_cycle.iter().nth(0).unwrap().clone(),
Some(x) => x.clone(),
};
self.props.handle.reduce(move |state| state.theme = next_theme.to_string());
},
Msg::ToggleLangDropdown => self.show_lang_dropdown = !self.show_lang_dropdown,
Msg::ToggleThemeDropdown => self.show_theme_dropdown = !self.show_theme_dropdown,
};
true
}
如果有人知道我第一次嘗試做錯了什么,那還是很酷的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.