我正在关注一个在线教程,该教程使用next-routes定义自定义通配符路由,但无法正常工作。
我的server.js文件:
const { createServer } = require("http");
const next = require("next");
const app = next({
dev: process.env.NODE_ENV !== "production"
});
const routes = require("./routes");
const handler = routes.getRequestHandler(app);
app.prepare().then(() => {
createServer(handler).listen(3000, e => {
if(e) throw e;
console.log("Ready on localhost:3000");
})
})
我的route.js文件:
const routes = require("next-routes")();
routes.add("/campaigns/:address(0x[0-9a-fA-F]+)", "campaigns/show");
module.exports = routes;
我的广告系列/show.js
import React from "react";
class CampaignShow extends React.Component {
static getInitialProps(props) {
return {}
}
render() {
return (
<h3>Campaign Show</h3>
)
}
}
export default CampaignShow
当我从应用导航至http://localhost:3000/campaigns/0x78E6Fdf23DBA11016c658cc93C4bBb4F63bDAf25时,一切正常,并且看到了我希望看到的页面
但是,如果我尝试直接打开该链接,则服务器端渲染将不起作用,并显示404错误页面。虽然控制台显示的不是非常有用的错误:
Page does not exist: /campaigns/0x78E6Fdf23DBA11016c658cc93C4bBb4F63bDAf25
Error: Page does not exist: /campaigns/0x78E6Fdf23DBA11016c658cc93C4bBb4F63bDAf25
at http://localhost:3000/_next/1543962700127/page/campaigns/0x78E6Fdf23DBA11016c658cc93C4bBb4F63bDAf25:3:21
at register (http://localhost:3000/_next/1543962700127/main.js:20505:24)
at PageLoader.registerPage (http://localhost:3000/_next/1543962700127/main.js:20530:9)
at http://localhost:3000/_next/1543962700127/main.js:18414:14
at Array.forEach (<anonymous>)
at Object.<anonymous> (http://localhost:3000/_next/1543962700127/main.js:18410:30)
at __webpack_require__ (http://localhost:3000/_next/1543962700127/manifest.js:714:31)
at fn (http://localhost:3000/_next/1543962700127/manifest.js:117:20)
at Object.<anonymous> (http://localhost:3000/_next/1543962700127/main.js:13708:9)
at __webpack_require__ (http://localhost:3000/_next/1543962700127/manifest.js:714:31)
GET http://localhost:3000/campaigns/0x78E6Fdf23DBA11016c658cc93C4bBb4F63bDAf25 404 (Not Found)
我在做什么错了?
答案 0 :(得分:0)
将此行添加到您的show
import {withRouter} from 'next/router'
并将您的导出更新为此:
export default withRouter(CampaignShow)
答案 1 :(得分:0)
根据 Next.js docs,getInitialProps
应放置在 React 组件之外,如下所示:
import React from "react";
class CampaignShow extends React.Component {
render() {
return (
<h3>Campaign Show</h3>
)
}
}
Page.getInitialProps = async (ctx) => {
return { }
}
export default CampaignShow
请注意,getInitialProps
仅在初始页面加载时进行服务器端提取,并在客户端路由时进行客户端提取。