DEV Community

panfan
panfan

Posted on

Next.js - Imperative Routing

到目前为止,使用 Link 组件从一个页面导航到另一个页面。使用 Router 组件也可以实现相同的功能。

更新index.js

import Router from 'next/router'
import Head from 'next/head'

function HomePage(props) {
  return (
    <>
      <Head>
        <title>Welcome to Next.js!</title>
      </Head>
      <div>Welcome to Next.js!</div>
      <span onClick={() => Router.push('/posts/one')}>First Post</span>
      <br />
      <div>Next stars: {props.stars}</div>
      <img src="/logo.png" alt="Logo" />
    </>
  )
}

export async function getServerSideProps(context) {
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const json = await res.json()
  return {
    props: {stars: json.stargazers_count}
  }
}

export default HomePage
Enter fullscreen mode Exit fullscreen mode

启动服务

npm run dev
Enter fullscreen mode Exit fullscreen mode

验证结果

iZhXRv

Top comments (0)