rust 使用Yew中的wasm_timer重复执行回调

zqdjd7g9  于 2023-05-29  发布在  其他
关注(0)|答案(1)|浏览(198)

我对Rust还是个新手,很难理解未来。我想在浏览器中实现一个“计时器应用程序”,为此我使用了https://yew.rs/。对于计时器,我尝试使用https://github.com/tomaka/wasm-timer/,但没有文档和示例。看起来用法应该是显而易见的,但我不明白。
我假设我必须做这样的事情:

let i = Interval::new(core::time::Duration::from_millis(250));

这将创建一个每250ms触发一次的Interval。什么是解雇?如何指定我的回调?我会期待类似的东西:

i.somehow_specify_callback(|| { ... executed every 250ms ...});

我的感觉是,我在某种程度上走错了路,没有得到把握 rust 期货.一个关于如何让Interval执行一些代码的工作示例将非常受欢迎。

uz75evzq

uz75evzq1#

下面是Timer组件的伪代码示例:

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/hooks#pre-defined-hooks

相关问题