我希望我的下一个路由在从server.js(服务器端)运行以及在具有Link的链接端运行时,能够正常处理未找到的文件(实际上未找到路由)。我有一个解决方案,但是它体积很大,感觉好像我没有尽我所能。
我将粘贴在我的页面文件(pages / speakerdetail.js)下面,该文件确实可以正确处理服务器和客户端,但是在每个显示“未找到”的文件中必须具有自定义渲染方法似乎是错误的。
我也在仓库中以示例方式运行
https://github.com/pkellner/next-routes-problem
import React, {Component} from 'react';
import {Link} from '../routes'
import Router from 'next/router'
class speakerdetail extends Component {
static async getInitialProps({req,res,query}) {
console.log("getInitialProps speakerdetail");
let statusCode = 200;
let slugSpeaker = '';
let ccYear = '';
if (query && query.slugSpeaker) {
console.log("query.slugSpeaker:" + query.slugSpeaker);
slugSpeaker = query.slugSpeaker;
}
if (query && query.ccYear) {
console.log("query.ccYear:" + query.ccYear);
ccYear = query.ccYear;
}
if (slugSpeaker != 'douglas-crockford-1124' || ccYear != '2018') {
if (req) {
console.log("getInitialProps - res.redirect cause server");
statusCode = 404;
res.statusCode = 404;
} else {
console.log("getInitialProps - router.push cause client")
Router.push('/error404');
}
}
return {
slugSpeaker,
ccYear,
statusCode
};
}
render() {
if (this.props.statusCode == 404) {
return (
<div>Not Found</div>
)
}
return (
<div>
<b>speakerdetail {this.props.ccYear} {this.props.slugSpeaker} {this.props.statusCode}</b>
<hr/>
<Link route='/' >
<a>home</a>
</Link>
</div>
);
}
}
speakerdetail.propTypes = {};
speakerdetail.defaultProps = {};
export default speakerdetail;