使用紫杉框架的Web程序集出现未捕获错误



我正在使用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 == &current_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是";铁锈;然后我再次点击调用Msg::ChangeTheme的按钮,主题应该设置为";"轻";但相反,我的代码惊慌失措;未捕获错误:未定义";在浏览器控制台中。

我找到了一个解决方法;我没有使用数组和访问值,而是尝试做同样的任务,但只是使用迭代器,并确保更新函数不拥有函数本身之外的任何变量(我真的不知道这是否真的有必要…(

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
}

如果有人知道我第一次尝试做错了什么,那还是很酷的。

相关内容

最新更新