如果请求的页面没有底层服务器端资源,我正在服务器端呈现的页面中寻找处理 HTTP 404 的最佳实践。
例如,假设请求的页面是http://localhost:3000/places/5。在我的 SSG 实施中:
export async function getServerSideProps(context) {
const placeId = context.params.placeId;
const places = await getPlace(placeId);
if (!places.length) { /* is there anything here I can do to facilitate a 404? this place does not exist in the db */ }
return {
props: {
places[0],
},
};
}
Run Code Online (Sandbox Code Playgroud)
这应该是不言自明的,但如果在这种情况下请求的 id5不在我的数据库中,我该如何将其作为 HTTP 404 处理?
我正在使用 Next.js 开发 Django Rest 框架,但我陷入了从 API 获取数据的困境。我在这个 url 中有数据http://127.0.0.1:8000/api/campaigns,当我访问该 url 时,我会看到数据。
问题是当我使用 Next.js 获取并控制台数据时,我得到了undefined. 另外,当我尝试映射数据时,我收到错误:
未处理的运行时错误
错误:无法读取未定义的属性(读取“地图”)
这是我Index.js完成数据获取的文件:
import React from 'react'
export default function Index ({data}) {
console.log(data)
return (
<div>
<main>
<h1>Available Campaigns</h1>
{data.map((element) => <div key={element.slug}>
<div>
<div>
<img src={element.logo} height={120} width={100} alt="image" />
</div>
<div></div>
</div>
</div>)}
</main>
</div>
);
}
export async function getStaticProps() {
const response = await fetch("http://127.0.0.1:8000/api/campaigns");
const data = await response.json();
return {
props: …Run Code Online (Sandbox Code Playgroud) 删除状态中的元素后,组件不会重新渲染,但状态确实会发生变化。在组件中,您可以通过表单在数组(这是一个状态)中添加一个元素,查看数组中的所有元素,并使用按钮将其从状态中删除。因此,删除处于该状态的元素后,该组件不会重新渲染。以下是该组件的代码:
import React, { useEffect, useState } from 'react';
import {
Typography,
IconButton,
Button,
TextField,
Paper,
} from '@mui/material';
import {
CancelOutlined,
AddBoxOutlined,
VisibilityOutlined,
VisibilityOffOutlined,
} from '@mui/icons-material';
export default function Test1() {
const [subNames, setSubNames] = useState([]);
const [subName, setSubName] = useState('');
const [showSubForm, setShowSubForm] = useState(false);
const onSubNameChange = (e) => {
setSubName(e.target.value);
};
const onSubNameSubmit = () => {
if (!subName) return alert('Enter name!');
setSubNames((prev) => prev.concat({ name: subName }));
setShowSubForm(false);
setSubName('');
};
const subForm = ( …Run Code Online (Sandbox Code Playgroud) 我创建了一个使用该文件夹的全新 Next.js 应用程序app。然后,我安装了 Materiel UI 并开始使用文档中给出的示例。但我收到这个错误:
类型错误:createContext 仅适用于客户端组件。在文件顶部添加“use client”指令以使用它。
这是我的代码中文档的示例:
import Button from "@mui/material/Button";
export default function Home() {
return (
<div>
<Button variant="contained">Hello World</Button>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
我希望该按钮显示在我的页面上。我知道"use client"在顶部添加将修复错误,但我希望我的页面在服务器上渲染。
当我安装node-sassReact 项目时,出现以下错误。我尝试了很多东西,但没有一个起作用。我尝试删除它并再次安装它,我尝试启动一个新项目,但它仍然无法正常工作。我将所有内容更新为最新版本:node.js 更新为v16.14.0,npm 更新为v8.3.1。
npm ERR! code 1
npm ERR! path C:\Users\XXXXX\Documents\GitHub\XXXXX\Frontend\node_modules\node-sass
npm ERR! command failed
npm ERR! command C:\Windows\system32\cmd.exe /d /s /c node scripts/build.js
npm ERR! Building: C:\Program Files\nodejs\node.exe C:\Users\XXXXX\Documents\GitHub\XXXXX\Frontend\node_modules\node-gyp\bin\node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp verb cli [
npm ERR! gyp verb cli 'C:\\Program Files\\nodejs\\node.exe',
npm ERR! gyp verb cli 'C:\\Users\\XXXXX\\Documents\\GitHub\\XXXXX\\Frontend\\node_modules\\node-gyp\\bin\\node-gyp.js',
npm ERR! gyp verb cli 'rebuild',
npm …Run Code Online (Sandbox Code Playgroud) 我正在学习 NestJS,这是我的简单服务:
import { Injectable } from '@nestjs/common';
const userMock = [{ account: 'dung', password: '12345678' }];
@Injectable()
export class UserService {
getUser() {
return userMock
}
}
Run Code Online (Sandbox Code Playgroud)
我不太了解@InjectableNestJS。一些教程告诉@Injectable我们@Controller知道这是一个安装并且可以将其用作依赖项注入。但当我删除它时,它仍然有效。
请举例说明有@Injectable和没有的区别@Injectable
我正在开发一个使用 Google reCAPTCHA 的 React.js/Next.js 项目。我的前端似乎正在工作(我知道,因为我一路上设置了打印语句),但后端在我的本地终端中给了我这个错误:
错误 - 'src\app\api\recaptcha\route.ts' 中没有导出 HTTP 方法。为每个 HTTP 方法导出命名导出。
我的开发工具中也出现错误:
'POST http://localhost:3000/api/recaptcha 405(不允许的方法)'
我相信这与另一个错误有关。
这是代码:
import { NextApiRequest, NextApiResponse } from 'next';
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import axios from 'axios';
const app = express();
app.use(cors());
app.use(bodyParser.json());
console.log('hi');
export async function postHandler(req: NextApiRequest, res: NextApiResponse){
if (req.method === 'POST') {
const { token } = req.body;
try {
const response = await axios.post(
`https://www.google.com/recaptcha/api/siteverifysecret=${process.env.NEXT_PUBLIC_RECAPTCHA_SECRET_KEY}&response=${token}`
);
console.log('you made it …Run Code Online (Sandbox Code Playgroud) /demo我的 Next.js 应用程序中有一条路线13,它使用App Router. 但我无法更改页面的标题(我得到的当前标题是 localhost:3000/demo)。
我有以下代码。
/demo/page.js:
'use client'
....
export const metadata = {
title: 'Demo - ModalJS',
};
export default Demo(){
return ...
}
Run Code Online (Sandbox Code Playgroud)
这'use client'正在造成问题,因为当我删除它时,标题会发生变化,但问题是我无法删除它,因为该组件使用onClick它会在没有“使用客户端”的情况下给出错误
里面的代码Demo如下:
export default function Demo() {
const [title, setTitle] = useState("Title of your modal");
const [desc, setDesc] = useState("You description goes here");
const [theme, setTheme] = useState("light");
const handleclick = ()=>{
const modal = new ModalJS( ... stuff related …Run Code Online (Sandbox Code Playgroud) 例如,我们曾经使用getServerSideProps重定向到页面组件中的 404 页面,如下所示:
// pages/index.js
export async function getServerSideProps(context) {
const placeId = context.params.placeId;
const places = await getPlace(placeId);
if (!places.length) {
return {
notFound: true,
}
}
return {
props: {
places[0],
},
};
Run Code Online (Sandbox Code Playgroud)
有了 Next.js13和app目录,我们就有了服务器组件。getServerSideProps由于不再使用,如何重定向到 404 页面?
我遇到的一个常见用例是在布局中使用一个按钮来切换子项中的某些内容。例如,您可以在持久布局中设置一个通知按钮,该按钮会在主应用程序中打开侧窗格。
理想情况下,您可以将isNotificationsPaneOpen状态传递给子级并让他们渲染窗格。然而,Next 13 beta 文档说这是不可能的:
在父布局与其子布局之间传递数据是不可能的。但是,您可以在一个路由中多次获取相同的数据,React 会自动删除请求的重复数据,而不会影响性能。
在后端保持这种切换状态似乎是一种重大的矫枉过正,而且感觉不自然。后端不必知道前端打开或关闭通知面板。
在我看来,这是一个足够常见的用例,人们经常会遇到这个问题。
人们通常应该如何看待这一问题?
具体例子:
// in layout.tsx
export default function NavbarLayout({
children,
}: {
children: React.ReactNode,
}) {
const [isNotificationsPaneOpen, setIsNotificationsPaneOpen]= useState(false);
return (
<div>
<nav>
<button onClick={()=>setIsNotificationsPanelOpen((prevValue)=>!prevValue)}>Notifications</button>
</nav>
{/* How do I pass isNotificationsPaneOpen to children? */}
{children}
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
所以在页面中:
// in page.tsx
interface PageProps {
isNotificationsPaneOpen: boolean;
}
function Page({isNotificationsPaneOpen}:PageProps):JSX.Element {
// render something conditionally with isNotificationsPaneOpen
...
}
Run Code Online (Sandbox Code Playgroud)
目前的解决方案
如果依赖于布局状态的组件在页面之间保持相同(如通知面板示例),则将其包含在此处是有意义的。但其他示例(例如在布局中切换亮/暗模式)在每个页面上呈现不同的内容,因此这不是通用的解决方案。
localstorage …reactjs ×9
javascript ×8
next.js ×7
node.js ×2
typescript ×2
django ×1
material-ui ×1
nestjs ×1
node-sass ×1
npm ×1
rest ×1
sass ×1