NextJS判断当前执行代码段是在服务端组件还是客户端组件

NextJS中定义的函数,可能会存在同时被服务器端组件和客户端组件同时使用的场景,如下代码可以区分当前执行代码所在场景。

nextjs 13中推荐使用

if(typeof window == 'undefined') {
    console.log("server component")
}
else {
    console.log("client component")
}

下面方法老版本中可以使用,但是在新版本中已经提示@deprecated — Use typeof window instead

if(process.browser) {
    
} else {
    
}

你可能感兴趣的:(NextJS开发教程,前端,reactjs)