我有一个使用快速自定义浏览器用下一个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);
I have already checked the next.js docs and it has this implementation which uses the node http module.我通过复制文档示例中的某些部分来实现了这段代码。但是,当我使用。
转到文章页面时,似乎仍然会导致页面重新加载。答案 0 :(得分:1)
替换
<Link
href={`/blog/${dynamicPostSlug}`}>
与
<Link
href={`/blog/post?postslug=${dynamicPostSlug}`}
as={`/blog/${dynamicPostSlug}`}>
getInitialProps
应该从参数中获取查询,而不是要求。
static async getInitialProps({ query }) {
try {
const res = await fetch(`http://localhost/api/posts/${query.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');
}
}