用 Inertia 渲染笔记本

在 web 处理器里返回 inertia::render,并用 serde skip 把密码哈希挡在页面之外。

这门课仍然是 0.x 测试版。起步应用用 Inertia、React、TypeScript、Tailwind 和 Vite 渲染页面。Inertia 不是第二套路由器。Laravel 处理器返回组件名和 props。组件放在 resources/js/pages。

Inertia 只在经过 HandleInertiaRequests 的路由上工作。新应用在 src/app.rs 里把这个中间件加到 web 分组。在 api 路由上调用 inertia::render 会返回服务器错误。把笔记本留在 web.rs。

列表页

use laravel::inertia::{self, Page, props};
use laravel::prelude::*;

use crate::models::Note;

pub async fn index() -> laravel::Result<Page> {
    let notes = Note::query()
        .with(Note::user)
        .latest(Note::created_at)
        .limit(20)
        .get()
        .await?;

    Ok(inertia::render("Notes/Index", props! { notes }))
}

"Notes/Index" 对应 resources/js/pages/Notes/Index.tsx。props! 可以按名字接受局部变量。这样列出的变量是借用,所以后面仍能使用 notes。键保持你写下的大小写。

每个 prop 对检查页面的人都是可见的。只发送屏幕需要的字段。PasswordHash 和 RememberToken 不实现 Serialize,所以只有给这些字段加上 #[serde(skip)],User 才能进入页面。起步应用已经跳过了它们。如果你给 Note 加了自己的秘密字段,也要跳过。Inertia 不会替你丢掉它。

作者会出现在 notes 里,是因为你调用了 .with(Note::user)。这个关联会解引用成 User。序列化页面时如果关联没加载,会 panic,消息和数据课里的 “isn’t loaded” 相同。

type Note = {
    id: number;
    title: string;
    body: string;
    user: { id: number; name: string };
};

export default function Index({ notes }: { notes: Note[] }) {
    return (
        <ul>
            {notes.map((note) => (
                <li key={note.id}>{note.title} — {note.user.name}</li>
            ))}
        </ul>
    );
}

创建表单用 Inertia 指南里的 <Form>。它提交到你的处理器,并期望一次重定向:

import { Form } from "@inertiajs/react";

<Form action="/notes" method="post">
    {({ errors, processing }) => (
        <>
            <input type="text" name="title" />
            {errors.title && <p>{errors.title}</p>}
            <textarea name="body" />
            {errors.body && <p>{errors.body}</p>}
            <button type="submit" disabled={processing}>Save</button>
        </>
    )}
</Form>

不要在表单上放 user_id。StoreNote 会忽略它,处理器从会话设置 user。web 路由上的验证失败会带着错误重定向回去。<Form> 读取这些错误。JSON 客户端仍然得到 422。这个区分来自验证指南,不是 React 页面决定的。

laravel dev 已经在跑 Vite。保存 TSX 会热更新。保存 Rust 处理器会重建服务器。组件名和文件路径不一致时,页面无法解析。字符串和路径就是契约。

检验一下

登录后打开 /notes。React 页面应列出标题,页面 JSON 里不应出现密码哈希。

返回路线图