gpt4 book ai didi

reactjs - Next.js-express 动态路由导致页面重新加载

转载 作者:行者123 更新时间:2023-12-03 13:28:40 33 4
gpt4 key购买 nike

我有一个使用快速自定义浏览器使用 next 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.我通过复制文档示例中的一些部分在 Express 上实现了此代码。然而,当我使用 .

进入文章页面时,它似乎仍然导致页面重新加载。

最佳答案

替换

<Link 
href={`/blog/${dynamicPostSlug}`}>

<Link 
href={`/blog/post?postslug=${dynamicPostSlug}`}
as={`/blog/${dynamicPostSlug}`}>

getInitialProps 应该从参数而不是 req 中获取查询。

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');
}
}

关于reactjs - Next.js-express 动态路由导致页面重新加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55014235/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com