dioxus-knowledge-patch

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Dioxus 0.5+ Knowledge Patch

Dioxus 0.5+ 知识补丁

Claude's baseline knowledge covers Dioxus through 0.4.x. This skill provides features from 0.5 (2024) onwards.
Claude的基础知识覆盖到Dioxus 0.4.x版本。本技能提供0.5版本(2024年及以后)的新特性。

Quick Reference

快速参考

Component Syntax (0.5+)

组件语法(0.5+)

Old (0.4)New (0.5+)
fn App(cx: Scope) -> Element
fn App() -> Element
cx.use_hook()
use_signal()
,
use_memo()
use_state
,
use_ref
Signal<T>
(always Copy)
Per-platform launchers
dioxus::launch(App)
旧版(0.4)新版(0.5+)
fn App(cx: Scope) -> Element
fn App() -> Element
cx.use_hook()
use_signal()
,
use_memo()
use_state
,
use_ref
Signal<T>
(始终支持Copy)
各平台启动器
dioxus::launch(App)

Signals

信号(Signals)

OperationSyntax
Create
let count = use_signal(|| 0);
Read (subscribes)
count.read()
or
count()
Read (no subscribe)
count.peek()
Write
count.write()
,
count.set(5)
,
count += 1
Global
static THEME: GlobalSignal<T> = GlobalSignal::new(|| ...)
Mapped
user.map(|u| &u.name)
See
references/signals-hooks.md
for hooks, effects, resources, coroutines.
操作语法
创建
let count = use_signal(|| 0);
读取(订阅更新)
count.read()
count()
读取(不订阅更新)
count.peek()
写入
count.write()
,
count.set(5)
,
count += 1
全局信号
static THEME: GlobalSignal<T> = GlobalSignal::new(|| ...)
映射信号
user.map(|u| &u.name)
更多关于钩子、副作用、资源、协程的内容,请查看
references/signals-hooks.md

RSX Syntax

RSX语法

PatternExample
Conditional
if show { Header {} }
Conditional attr
class: if active { "active" }
List with key
for item in items { li { key: "{item.id}", ... } }
Children prop
fn Card(children: Element) -> Element
Optional prop
#[props(default)] disabled: bool
Prop into
#[props(into)] id: String
See
references/rsx-patterns.md
for attributes, events, prop spreading.
模式示例
条件渲染
if show { Header {} }
条件属性
class: if active { "active" }
带key的列表
for item in items { li { key: "{item.id}", ... } }
子元素属性
fn Card(children: Element) -> Element
可选属性
#[props(default)] disabled: bool
转换属性
#[props(into)] id: String
更多关于属性、事件、属性展开的内容,请查看
references/rsx-patterns.md

Assets (0.6+)

资源管理(0.6+)

rust
const LOGO: Asset = asset!("/assets/logo.png");
const HERO: Asset = asset!("/hero.png", ImageAssetOptions::new()
    .format(ImageFormat::Avif).preload(true));
const STYLES: Asset = asset!("/app.css", CssAssetOptions::new().minify(true));
rust
const LOGO: Asset = asset!("/assets/logo.png");
const HERO: Asset = asset!("/hero.png", ImageAssetOptions::new()
    .format(ImageFormat::Avif).preload(true));
const STYLES: Asset = asset!("/app.css", CssAssetOptions::new().minify(true));

Server Functions (0.7+)

服务器函数(0.7+)

FeatureSyntax
Basic
#[server] async fn get_data() -> Result<T>
Route params
#[get("/api/users/{id}")] async fn get_user(id: u32)
Query params
#[get("/search?query")] async fn search(query: String)
Middleware
#[server] #[middleware(AuthLayer)]
Extractors
async fn auth(headers: HeaderMap, cookies: Cookies)
See
references/fullstack.md
for WebSocket, SSR, streaming, server config.
特性语法
基础用法
#[server] async fn get_data() -> Result<T>
路由参数
#[get("/api/users/{id}")] async fn get_user(id: u32)
查询参数
#[get("/search?query")] async fn search(query: String)
中间件
#[server] #[middleware(AuthLayer)]
提取器
async fn auth(headers: HeaderMap, cookies: Cookies)
更多关于WebSocket、SSR、流式渲染、服务器配置的内容,请查看
references/fullstack.md

Router

路由

rust
#[derive(Routable, Clone, PartialEq)]
enum Route {
    #[route("/")]
    Home {},
    #[route("/user/:id")]
    User { id: u32 },
    #[route("/files/:..path")]     // Catch-all
    Files { path: Vec<String> },
}
See
references/router.md
for layouts, navigation, nested routes.
rust
#[derive(Routable, Clone, PartialEq)]
enum Route {
    #[route("/")]
    Home {},
    #[route("/user/:id")]
    User { id: u32 },
    #[route("/files/:..path")]     // 通配路由
    Files { path: Vec<String> },
}
更多关于布局、导航、嵌套路由的内容,请查看
references/router.md

CLI Commands

CLI命令

CommandPurpose
dx serve
Dev server with hot-reload
dx serve --platform ios
iOS simulator
dx build --release
Production build
dx bundle
Package for distribution
dx serve --wasm-split
Route-based code splitting
See
references/cli-desktop.md
for desktop config, platform args.
命令用途
dx serve
带热重载的开发服务器
dx serve --platform ios
iOS模拟器
dx build --release
生产环境构建
dx bundle
打包用于分发
dx serve --wasm-split
基于路由的代码分割
更多关于桌面端配置、平台参数的内容,请查看
references/cli-desktop.md

Reference Files

参考文档

FileContents
signals-hooks.md
Signals, use_memo, use_effect, use_resource, context
rsx-patterns.md
RSX syntax, props, events, conditionals, lists
fullstack.md
Server functions, SSR, WebSocket, extractors
router.md
Routes, layouts, navigation, parameters
cli-desktop.md
CLI commands, desktop config, platforms
文件内容
signals-hooks.md
信号、use_memo、use_effect、use_resource、上下文
rsx-patterns.md
RSX语法、属性、事件、条件渲染、列表
fullstack.md
服务器函数、SSR、WebSocket、提取器
router.md
路由、布局、导航、参数
cli-desktop.md
CLI命令、桌面端配置、平台

Critical Knowledge

核心知识点

Element is Result (0.6+)

Element 为Result类型(0.6+)

Use
?
anywhere - propagates to ErrorBoundary:
rust
#[component]
fn Profile(id: u32) -> Element {
    let user = get_user(id)?;  // Early return on error
    rsx! { "{user.name}" }
}
可在任意位置使用
?
- 错误会传播到ErrorBoundary:
rust
#[component]
fn Profile(id: u32) -> Element {
    let user = get_user(id)?;  // 出错时提前返回
    rsx! { "{user.name}" }
}

Suspense for Async

异步操作的Suspense

rust
rsx! {
    SuspenseBoundary {
        fallback: |_| rsx! { "Loading..." },
        AsyncChild {}
    }
}

fn AsyncChild() -> Element {
    let data = use_resource(fetch_data).suspend()?;
    rsx! { "{data}" }
}
rust
rsx! {
    SuspenseBoundary {
        fallback: |_| rsx! { "加载中..." },
        AsyncChild {}
    }
}

fn AsyncChild() -> Element {
    let data = use_resource(fetch_data).suspend()?;
    rsx! { "{data}" }
}

Document Head

文档头部管理

rust
use dioxus::document::{Title, Link, Meta};

rsx! {
    Title { "My Page" }
    Meta { name: "description", content: "..." }
    Link { rel: "stylesheet", href: asset!("/style.css") }
}
rust
use dioxus::document::{Title, Link, Meta};

rsx! {
    Title { "我的页面" }
    Meta { name: "description", content: "..." }
    Link { rel: "stylesheet", href: asset!("/style.css") }
}

Stores for Nested State (0.7+)

嵌套状态的Store(0.7+)

rust
#[derive(Store)]
struct AppState {
    users: BTreeMap<String, User>,
}

#[component]
fn UserList(state: Store<AppState>) -> Element {
    let users = state.users();
    rsx! {
        for (id, user) in users.iter() {
            UserRow { key: "{id}", user }  // Only changed items re-render
        }
    }
}
rust
#[derive(Store)]
struct AppState {
    users: BTreeMap<String, User>,
}

#[component]
fn UserList(state: Store<AppState>) -> Element {
    let users = state.users();
    rsx! {
        for (id, user) in users.iter() {
            UserRow { key: "{id}", user }  // 仅变化的项会重新渲染
        }
    }
}

CSS Modules (0.7.3+)

CSS Modules(0.7.3+)

rust
css_module!(Styles = "/styles.module.css", AssetOptions::css_module());

rsx! {
    div { class: Styles::container,  // Typed, compile-checked
        p { class: Styles::title, "Hello" }
    }
}
rust
css_module!(Styles = "/styles.module.css", AssetOptions::css_module());

rsx! {
    div { class: Styles::container,  // 类型安全,编译时检查
        p { class: Styles::title, "你好" }
    }
}

Fullstack Server Setup

全栈服务器设置

rust
use axum::Router;
use dioxus::prelude::*;

#[tokio::main]
async fn main() {
    let app = Router::new()
        .serve_static_assets("dist")
        .serve_dioxus_application(ServeConfig::new(), App);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
rust
use axum::Router;
use dioxus::prelude::*;

#[tokio::main]
async fn main() {
    let app = Router::new()
        .serve_static_assets("dist")
        .serve_dioxus_application(ServeConfig::new(), App);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Reactivity Gotchas

响应式陷阱

Memos in attributes don't subscribe properly:
rust
// BAD: Won't update
let style = use_memo(move || format!("color: {}", color()));
rsx! { div { style: style } }

// GOOD: Direct signal read
rsx! { div { style: format!("color: {}", color()) } }
Use individual CSS properties:
rust
// GOOD: Proper reactivity
rsx! {
    p {
        font_weight: if bold() { "bold" } else { "normal" },
        text_align: "{align}",
    }
}
属性中的Memo无法正确订阅更新:
rust
// 错误:不会更新
let style = use_memo(move || format!("color: {}", color()));
rsx! { div { style: style } }

// 正确:直接读取信号
rsx! { div { style: format!("color: {}", color()) } }
使用独立的CSS属性:
rust
// 正确:响应式正常
rsx! {
    p {
        font_weight: if bold() { "bold" } else { "normal" },
        text_align: "{align}",
    }
}

Hot-Reload Boundaries

热重载边界

Instant reload: Literal values, text, formatted segments, attribute order, template structure
Requires rebuild: Rust logic, component structure, control flow conditions, struct field changes
即时重载: 字面量值、文本、格式化片段、属性顺序、模板结构
需要重新构建: Rust逻辑、组件结构、控制流条件、结构体字段变更