next.js - NextJS, How to route to internal and external page in NextJS?
问题描述
I have a reactjs app with NextJS and need some help with routing
Structure
Pages
-- location.js
-- selectLocation.js
URL: location?city=Birmingham&state=AL
1: I want to redirect the user to /selectLocation when no argument is pass
2: I want to redirect the user to "www.google.com" -- if the city=augusta
otherwise, just render the page
This is what is working but I not sure if is the correct method
Can you please let me know.
export default class extends Component {
static getInitialProps({ query: { city, state } }) {
return { city: city, state: state };
}
componentDidMount() {
if (!this.props.city) {
Router.push('INTERNAL URL')
} else {
if (this.props.city === "augusta") {
window.location = 'https://www.google.com'
}
}
}
render() {
if (!this.props.city ||this.props.city === "augusta"){
return null
}else{
return(
<div>...</div>
)
}
}
}
解决方案
It is better to make the redirect from getInitialProps
, it runs on the server (for first page render) & on the client (for rest of the pages).
export default class extends Component {
static getInitialProps({query: {city, state}, res}) {
if (!this.props.city || this.props.city === 'augusta') {
if (res) {
// server side redirection
return res.redirect(301, !this.props.city ? 'INTERNAL URL' : 'https://www.google.com');
} else {
// client side
if (!this.props.city) {
return Router.push('INTERNAL URL');
} else {
window.location = 'https://www.google.com';
}
}
}
return {city: city, state: state};
}
render() {
return <div>...</div>;
}
}
推荐阅读
- c++ - 带有热图像的 C++ 双三次插值
- android - android通过bundle将数据从片段传递到适配器
- exception - Google 电子表格:updateChart 失败异常
- java - 自定义签名者正在签名什么?
- html - 带条件的 Excel 导出 maatwebsite
- linux - 在 Redhat Linux 中执行 top 命令时如何显示进程路径?
- x11 - 如何设置 VcXSrv 以与 WSL2 一起使用
- python - Dataframe.loc 不适用于多个索引,非常简单
- button - 有没有办法让按钮在第一次单击时更改一种颜色,然后在第二次单击时恢复为原始颜色?
- eclipse - 无法将服务器添加到 Eclipse Photon