【问题标题】:useRouter().push() refreshing the page in next jsuseRouter().push() 在下一个js中刷新页面
【发布时间】:2021-07-14 16:39:27
【问题描述】:

我在下一个 js 中使用节点 js 自定义服务器。在没有自定义服务器的情况下,useRouter().push() 在我的 Next Js 应用程序中运行良好。现在它刷新了我的应用程序。它不给我单页应用程序。我第一次使用自定义节点服务器。我做节点自定义服务器错了吗???是节点 js 自定义服务器的问题。 谁能帮帮我?

server.js

const express = require('express')
const next = require('next')
const vhost = require('vhost')
const port=process.env.PORT || 3000
const dev=process.env.NODE_ENV!=='production'
const app=next({dev})


const handle=app.getRequestHandler()

app.prepare().then(()=>{

  
    const Server=express()
    const landing=express()
    
 
    landing.get('/', (req, res) => {
        return app.render(req, res, '/main', req.query)
      })
    
      landing.get('/*', (req, res) => {
        return app.render(req, res, `/main${req.path}`, req.query)
      })
    
      landing.all('*', (req, res) => {
        return handle(req, res)
      })
     
        
       
        Server.use(vhost('www.lvh.me', landing))
        Server.use(vhost('lvh.me', landing))
        Server.use(vhost(`localhost`, landing))
       
      Server.listen(port,(err)=>{
        if(err) throw err
        console.log(`http://www.lvh.me:${port}`)


    })


})

pages/main/index.js

import Image from 'next/image'
import {useRouter} from 'next/router'
export default function Home(){
    const router=useRouter()
    const navigateTo=(to)=>{
        router.push(to)
    }
return <>
<button onClick={()=>navigateTo("/")}>Home</button>
<button onClick={()=>navigateTo("/contact")}> Contact</button>
</>
}

_app.js

import '../styles/globals.css'

function MyApp({ Component, pageProps }) {

  return <Component {...pageProps} />
}

export default MyApp

【问题讨论】:

    标签: javascript node.js reactjs next.js


    【解决方案1】:

    请使用此代码可能是正确的

    import Image from 'next/image'
    import {useRouter} from 'next/router'
    export default function Home(){
        const router=useRouter()
        const navigateTo=(to)=>{
            router.push(`${to}`)
        }
    return <>
    <button onClick={()=>navigateTo("/")}>Home</button>
    <button onClick={()=>navigateTo("/contact")}> Contact</button>
    </>
    }
    

    【讨论】:

      【解决方案2】:

      UseRouter().push() 仅在 pages 文件夹中查找路由。当我路由到主文件夹内的页面时,它不起作用。现在,Page 渲染一次,在进一步的路由中不渲染,UseEffect 只实现一次。

      工作代码:

      import Image from 'next/image'
      import {useRouter} from 'next/router'
      export default function Home(){
          const router=useRouter()
          const navigateTo=(to)=>{
              router.push(/main${to},${to}) 
          }
      return <>
      <button onClick={()=>navigateTo("/")}>Home</button>
      <button onClick={()=>navigateTo("/contact")}> Contact</button>
      </>
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-03
        • 2021-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多