gpt4 book ai didi

reactjs - NextJS API目录和useState

转载 作者:行者123 更新时间:2023-12-02 18:10:36 31 4
gpt4 key购买 nike

我想得到

const [data, setData] = React.useState('');
const [pointdata, setPointData] = React.useState('');

在我的 API 目录中。但是,每次我尝试运行代码时,我都会得到 Cannot read properties of null (reading 'useState'

但是,相同的代码在 /page/myfile.js

中工作正常

我如何将 useStateuseEffect 放在 API 目录中,或者它们是另一种方法吗?

为什么它是 API 文件,因为我们正在向其发布表单数据。

import React, { useState } from "react";
export default async function gll(req, res) {
const [data, setData] = React.useState('');
const [pointdata, setPointData] = React.useState('');

}

最佳答案

您不能在 api 目录中使用 useState 和/或 useEffect。由于 React 是一个前端库,您只能在客户端代码中使用它的钩子(Hook),即 /page/[fileName].js。您在 /api/[fileName].js 中编写的代码是后端代码,因此您不能在那里使用 React.js Hook

根据官方 Next.js 文档。

API routes provide a solution to build your API with Next.js.

Any file inside the folder pages/api is mapped to /api/* and will betreated as an API endpoint instead of a page.

了解更多信息。访问API Routes | Next.js

关于reactjs - NextJS API目录和useState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72414041/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com