我有一个使用快速自定义浏览器的下一个js创建的博客应用程序。当我单击链接以路由到“ / blog / article-1”时,它会在到达该页面时刷新该页面。我如何避免这种情况?
server.js文件
const express = require('express');
const next = require('next');
const port = 80;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const compression = require('compression');
app.prepare()
.then(() => {
const server = express();
server.use(compression());
server.get('/blog', (req, res) => app.render(req, res, '/blog', req.query));
server.get('/blog/:postslug', (req, res) => {
const params = { postslug: req.params.postslug }
return app.render(req, res, '/blog/post', params)
});
server.get('*', (req, res) => handle(req, res));
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
链接到文章的文件
import React, { Fragment } from 'react';
import Link from 'next/link';
export default (props) => {
return (
<Fragment>
<Link href={`/blog/${dynamicPostSlug}`}>
<a>
Go to article
</a>
</Link>
</Fragment>
);
};
帖子出现的文件
import React, { Component, Fragment } from 'react';
import { withRouter } from 'next/router';
import 'isomorphic-unfetch';
class post extends Component {
static async getInitialProps({ req }) {
try {
const res = await fetch(`http://localhost/api/posts/${req.params.postslug}`, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
});
const json = await res.json();
return { data: json.data };
} catch (err) {
console.log('err');
}
}
render() {
const { data } = this.props;
return (
<Fragment>
<PostContentComesHere data={data}/>
</Fragment>
);
}
}
export default withRouter(post);
我已经检查了next.js文档,它具有使用节点http模块的实现。我通过复制文档示例中的某些部分在express上实现了此代码。但是,当我使用转到文章页面时,似乎仍然会导致页面重新加载。