我正在使用“使用服务器端渲染构建 React 应用程序”一书学习 nextjs
在此,我正在构建基本的反应应用程序,其中索引页面链接到关于页面。
该项目package.json
——
{
"name": "my-next-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "next",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"next": "^13.4.19",
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
pages/index.js
是 -
import React from "react";
import GetLink from "../sharedComponents/DynamicRouter";
function MyComponent() {
return (
<div>
<p>Hello from Next.js</p>
<GetLink title='Page 1'></GetLink>
<GetLink title='Page 2'></GetLink>
<GetLink title='Page 3'></GetLink>
</div>
);
};
export default MyComponent;
sharedComponents/DynamicRouter.js
是 -
import React from "react";
import Link from "next/link";
function GetLink(props) {
return (
<div>
<Link href={'/SecondPage?content=${props.title}'}>{props.title}</Link>
</div>
);
}
pages/SecondPage.js
是 -
export default (props) => {
console.log(JSON.stringify(props));
return (
<h1>
Welcome to {props.url}
</h1>
)};
当我单击page 1
类似的网址时,它会重定向到 ishttp://localhost:3000/SecondPage?content=${props.title}
而我认为它应该重定向到http://localhost:3000/SecondPage?content=page1
知道如何解决这个问题吗?
您的文件中有错误
sharedComponents/DynamicRouter.js
。您需要使用``(称为反引号)而不是''。
原因是因为变量扩展仅发生在``之间。
我已经修复了你的代码: