如何在ReactJ中获取项目的主要URL

发布于 2025-02-14 02:12:22 字数 402 浏览 0 评论 0原文

我正在与ReactJ一起工作,我想获得我的项目的fullPath/hostName/baseurl(在组件文件中),我该怎么做?我尝试了以下代码,但不工作,给我以下错误,

"Unexpected token `{`. Expected * for generator"

我尝试了以下错误,以遵循以下代码

import absoluteUrl from 'next-absolute-url';
class Header extends Component {
const { origin } = absoluteUrl(req)
const apiURL = ${origin}
render() 
    {
        ...//my code
    }   
}

I am working with reactjs and i want to get fullpath/hostname/baseurl of my project (inside component file),How can i do this ?I tried with following code,but not working,giving me following error

"Unexpected token `{`. Expected * for generator"

I tried with following code

import absoluteUrl from 'next-absolute-url';
class Header extends Component {
const { origin } = absoluteUrl(req)
const apiURL = ${origin}
render() 
    {
        ...//my code
    }   
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月静好 2025-02-21 02:12:23

如何使用窗口对象。

注意:使用窗口时,请在下面的情况下将其包裹在下面的情况下,否则在使用SSR时会出错。

import '../styles/globals.css';

function MyApp({ Component, pageProps }) {
  let fullPath = '';
  if (typeof window !== undefined) {
    fullPath = window.location.hostname;
  }
  console.log(fullPath);
  return <Component {...pageProps} className={fullPath === 'insert your path here' ? 'insert class to apply if true' : 'insert class to apply if false'}/>;
}

export default MyApp;

<

How about using the window object.

Note: when using window, do wrap it inside the below if condition, else it will error out when you're using SSR.

import '../styles/globals.css';

function MyApp({ Component, pageProps }) {
  let fullPath = '';
  if (typeof window !== undefined) {
    fullPath = window.location.hostname;
  }
  console.log(fullPath);
  return <Component {...pageProps} className={fullPath === 'insert your path here' ? 'insert class to apply if true' : 'insert class to apply if false'}/>;
}

export default MyApp;

stackblitz

风吹过旳痕迹 2025-02-21 02:12:23

因此,首先,请记住您的代码在客户端和服务器上运行,因此需要将对窗口的任何访问都包裹在检查中。

  if (typeof window !== 'undefined') {
    var path = location.protocol + '//' + location.host + '/someting'; // (or whatever)
  } else {
    // work out what you want to do server-side...
  }

So firstly, remember your code runs on client and server so any access to window needs to be wrapped in a check.

  if (typeof window !== 'undefined') {
    var path = location.protocol + '//' + location.host + '/someting'; // (or whatever)
  } else {
    // work out what you want to do server-side...
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文