我对锈病还是很陌生的,很难为未来做好准备。我想在浏览器中实现一个“计时器应用程序”,并使用https://yew.rs/。对于计时器,我尝试使用https://github.com/tomaka/wasm-timer/,但是没有文档,也没有示例。看起来这个用法应该是显而易见的,但我不明白。
我想我得做这样的事:
let i = Interval::new(core::time::Duration::from_millis(250));这应该会产生一个间隔,每250毫秒触发一次。但什么被解雇了?如何指定我的回调?我希望这样的事情:
i.somehow_specify_callback(|| { ... executed every 250ms ...});我的感觉是,不知何故,我走错了路,没有把握铁锈的未来。非常希望提供一个关于如何使Interval执行某些代码的工作示例。
发布于 2022-03-25 10:53:38
下面是计时器组件的伪代码示例:
enum SecondsStateAction {
Increment,
}
#[derive(Default)]
struct SecondsState {
seconds: usize,
}
impl Reducible for SecondsState {
/// Reducer Action Type
type Action = SecondsStateAction;
/// Reducer Function
fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
match action {
SecondsStateAction::Increment => Self { seconds: self.seconds + 1 }.into(),
}
}
}
#[function_component(Timer)]
pub fn timer() -> Html {
let seconds_state_handle = use_reducer(SecondsState::default);
use_effect_with_deps(
{
let seconds_state_handle = seconds_state_handle.clone();
move |_| {
// i intervals get out of scope they get dropped and destroyed
let interval = Interval::new(1000, move || seconds_state_handle.dispatch(SecondsStateAction::Increment));
// So we move it into the clean up function, rust will consider this still being used and wont drop it
// then we just drop it ourselves in the cleanup
move || drop(interval)
}
},
(), // Only create the interval once per your component existence
);
html! {<h1>{*seconds_state_handle}{" seconds has passed since this component got rendered"}</h1>}
}要了解关于代码中使用的钩子的更多信息,请访问https://yew.rs/docs/concepts/function-components/pre-defined-hooks
https://stackoverflow.com/questions/71270366
复制相似问题