Next.js 发送响应对象/主体,并从服务器操作重新验证路径

问题描述 投票:0回答:1

在重新验证

response
body
内的路径时是否可以发送
object
Server Action
/
Next.js

这是我的

Server Action
功能:

app/_actions/todo.tsx
addTodo
服务器操作:

export async function addTodo(prevState: any, formData: FormData) {
    const errors: {
        title?: string;
        description?: string;
    } = {};
    const title = formData.get('title')?.toString();
    const description = formData.get('description')?.toString();
    
    // Validate title and description

    if(errors.title || errors.description) {
        return { errors };
    }
    
    await dbConnect();

    const todo = new Todo({
        title,
        description
    });

    await todo.save();

    revalidatePath('/');

    return { todo: { title, description } };
}

有时,成功处理请求后,由

formState
钩子返回的
useFormState
对象具有
todo
属性,有时却没有。
所以它似乎工作不可靠。

更新

我发现破坏我的应用程序中的缓存无效行为的是使用根

loading.tsx
目录中的
app
文件。我想在加载路径
/
上的待办事项列表时显示“正在加载...”文本,因此我想保持这种方式,但
revalidatePath
并在服务器操作中返回响应正文仅在以下情况下才有效我删除了
app/loading.tsx
文件。如有任何帮助,我们将不胜感激!

这是

app
文件夹的文件结构:

File structure of app folder

  • app/page.tsx
import { Metadata } from 'next';
import TodoList from './_components/Todos/TodoList';

export const metadata: Metadata = {
    title: 'Todo App',
    description: 'Todo application for practicing Next.js',
};

export default function Home() {
    return (
        <TodoList />
    );
}
  • app/loading.tsx
export default function Loading() {
    return <p className="text-yellow-400">Loading...</p>;
}
  • app/_components/Todos/TodoList.tsx
'use server';
import { fetchTodos } from '@/app/_actions/todos';
import TodoListItem from './TodoListItem';

export default async function TodoList() {
    const fetchedTodos = await fetchTodos();

    if (!fetchedTodos.length) {
        return <p className="text-red-500">No todos were found!</p>;
    }

    return (
        <ul>
            {fetchedTodos.map((todo) => (
                <TodoListItem key={todo._id.toString()} todo={todo} />
            ))}
        </ul>
    );
}
  • app/_actions/todos.tsx
    fetchTodos
    服务器操作:
export async function fetchTodos() {
    await dbConnect();

    const todos = await Todo.find().sort({ createdAt: 'desc' });

    return todos;
}

该项目的 Github 存储库: https://github.com/caglartufan/next-todo

next.js
1个回答
0
投票

问题是您有

_loading.tsx
文件。它的名字应该是
loading.tsx
如果您阅读文档

特殊文件loading.js帮助您创建有意义的Loading UI 与反应悬念

如果将

console.log('loading');
添加到
Loadin
组件中,您将在服务器端看到日志语句:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.