fnapp(cx: Scope) -> Element { cx.render(rsx! { Router { onchange: move |_| log::info!("Route changed!"), ul { Link { to: "/", li { "Go home!" } } Link { to: "users", li { "List all users" } } Link { to: "blog", li { "Blog posts" } } } Route { to: "/", "Home" } Route { to: "/users", "User list" } Route { to: "/users/:name", User {} } Route { to: "/blog", "Blog list" } Route { to: "/blog/:post", BlogPost {} } Route { to: "", "Err 404 Route Not Found" } } }) }
我们在 app 下创建了一个 Router 组件,并将我们其他的所有组件都包含在里面。
Route 可以创建一个新的路由项,比如 Route { to: "/users", "User List" } 这一段代码:
当你访问的路径为 /users 时,则它会显示内容:User List (这里的 User List 可以为任何组件和元素)
而 Link 则用于创建一个切换到对应的路径中(在 Web 中它也会跳转到目标的 URL 中)
全局状态管理
Fermi 本来是一个独立的 crate 包,但在这个版本被引入到 Dioxus 中了(需要通过 features 添加)
// Create a single value in an "Atom" static TITLE: Atom<&str> = |_| "Hello";
// Read the value from anywhere in the app, subscribing to any changes fnapp(cx: Scope) -> Element { let title = use_read(&cx, TITLE); cx.render(rsx!{ h1 { "{title}" } Child {} }) }
// Set the value from anywhere in the app fnChild(cx: Scope) -> Element { let set_title = use_set(&cx, TITLE); cx.render(rsx!{ button { onclick: move |_| set_title("goodbye"), "Say goodbye" } }) }