首页 > 解决方案 > 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>
        )
     }

  }
}


标签: next.js

解决方案


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


推荐阅读