NextJS,如何在NextJS中路由到内部和外部页面?

时间:2020-06-04 13:02:59

标签: next.js

我有一个带有NextJS的reactjs应用,需要一些路由方面的帮助

结构

页面

-location.js

-selectLocation.js

URL :location?city = Birmingham&state = AL

1:我希望在不传递参数的情况下将用户重定向到/ selectLocation

2:我想将用户重定向到“ www.google.com”-如果city = augusta

否则,只需渲染页面

这是有效的方法,但我不确定是否正确的方法

你能告诉我吗?

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

  }
}


1 个答案:

答案 0 :(得分:0)

最好从getInitialProps进行重定向,它在服务器(用于第一页呈现)和客户端(用于其余页面)上运行。

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