组件生命周期

组件生命周期

使用 use_hook 初始化状态

use_hook 允许您为组件创建新状态。传递给 use_hook 的闭包将在组件首次渲染时被调用。每次组件重新渲染时,都会复用初始运行时创建的值。

rust 复制代码
fn UseHook() -> Element {
    // The closure that is passed to use_hook will be called once the first time the component is rendered
    let random_number = use_hook(|| {
        let new_random_number = random_number();

        log!("{new_random_number}");

        new_random_number
    });

    rsx! {
        div { "Random {random_number}" }
    }
}

重新渲染

当某个值发生变化时,您可以使用追踪值来重新渲染组件。

rust 复制代码
fn Rerenders() -> Element {
    let mut count = use_signal(|| 0);

    log!("Rerendering parent component with {}", *count.peek());

    rsx! {
        button { onclick: move |_| count += 1, "Increment" }
        // Since we read count here, the component will rerender when count changes
        Count { current_count: count() }
    }
}

// If the count prop changes, the component will rerender
#[component]
fn Count(current_count: i32) -> Element {
    log!("Rerendering child component with {current_count}");

    rsx! {
        div { "The count is {current_count}" }
    }
}

⚠️ 请勿在组件主体中修改状态

应避免在组件主体中更改状态。若在组件主体中读写状态,可能导致无限循环------组件因状态变更触发重新渲染,进而引发新一轮状态变更。

rust 复制代码
fn Bad() -> Element {
    let mut count = use_signal(|| 0);

    // ❌ 不要在组件主体中修改状态。这很容易导致无限循环!
    count += 1;

    rsx! { "{count}" }
}

相反,应使用 use_memouse_resource 或在 effect 中修改状态来推导状态。

使用 Effect

你可以使用effect在组件每次渲染时执行代码。

rust 复制代码
fn Effect() -> Element {
    // Effects 在组件渲染后执行
    // 可用于读取或修改渲染后的组件component
    use_effect(|| {
        log!("Effect ran");
        document::eval(&format!(
            "document.getElementById('effect-output').innerText = 'Effect ran'"
        ));
    });

    rsx! {
        div { id: "effect-output", "This will be changed by the effect" }
    }
}

使用 Drop 清理组件

组件被 drop 前,会释放其所有挂钩。可利用此 drop 行为清理组件使用的资源。若仅需 drop 效果,可使用 use_drop 挂钩。

rust 复制代码
fn TogglesChild() -> Element {
    let mut show = use_signal(|| true);

    rsx! {
        button { onclick: move |_| show.toggle(), "Toggle" }
        if show() {
            Child {}
        }
    }
}

fn Child() -> Element {
    // 你可以使用 use_drop 钩子来清理任何资源
    use_drop(|| {
        log!("Child dropped");
    });

    rsx! {
        div { "Child" }
    }
}
相关推荐
用户938515635071 分钟前
深入理解 Next.js:从 SPA 的 SEO 问题到约定式路由与 SSR 原理
前端·后端·全栈
红尘散仙6 小时前
浏览器不能监听端口、没有文件系统,凭什么能点对点传文件?
rust·webrtc·webassembly
nnerddboy8 小时前
Rust教程06:ESP32-rust环境搭建
开发语言·后端·rust
nnerddboy8 小时前
Rust教程03:函数,控制流与所有权
开发语言·后端·rust
nnerddboy9 小时前
Rust教程05:结构体,枚举与模式匹配
开发语言·网络·rust
特立独行的猫a12 小时前
我用 Rust + Tauri 2 复刻了 N_m3u8DL-CLI:一个 m3u8 多线程下载器
开发语言·后端·rust·m3u8·视频下载器·m3u8dl-cli
对象存储与RustFS12 小时前
大文件传到 48 GiB 就断:S3 分片上传的参数怎么算,以及那些没人清的残片
后端·rust·开源
程序员黑豆14 小时前
Java 内存存储机制:基本数据类型 vs 引用数据类型
前端·ai编程·全栈
程序员爱钓鱼14 小时前
Rust 生命周期案例详解:从编译错误到真实业务场景
前端·后端·rust
用户938515635071 天前
从前后端分离到前端接口工程:React + MockJS + Vite 解析
前端·后端·全栈