【问题标题】:Open a specific window when written "npm start"写入“npm start”时打开特定窗口
【发布时间】:2021-07-20 18:00:53
【问题描述】:

我想知道有没有办法,当写“npm start”时,浏览器不打开“localhost:3000”,而是像这样:“localhost:3000/param=1”?而且我不希望它只出现在我的电脑上。我希望当其他人安装我的反应应用程序时,他们也打开一个带有参数的窗口。有没有办法做到这一点?

【问题讨论】:

  • 你用过create-react-app吗?
  • 是的,我确实使用过。
  • 你使用的是 react-router 还是类似的东西?打开应用时重定向是否适合您?
  • 它是一个普通的反应应用程序,我想要的只是当我写“npm start”来启动我的应用程序时,被重定向到一个不同的链接,它有一些参数
  • 明白,但实际上并没有“正常”的反应应用。每个人都有不同的需求,做事也不同。有很多方法可以进行重定向。向我们提供有关您如何使用 React 及其众多组件的更多详细信息将有助于我们为您提供帮助。

标签: reactjs npm create-react-app


【解决方案1】:

你可以使用 React Router 并从起始页返回这个重定向:

<Redirect to="/param=1/" />

React Router Documentation

【讨论】:

    【解决方案2】:

    也许尝试在您的 package.json 中指定主页?

      "homepage": "http://mywebsite.com/relativepath",
    

    https://create-react-app.dev/docs/deployment/#building-for-relative-paths

    【讨论】:

      【解决方案3】:

      好的,实际上非常简单。我所需要的只是编写一个 JavaScript 文件,当用户在该链接上时将其重定向到链接“localhost:3000/?param=1”,但没有参数。这是javascript代码:

        // This is the variable where the url params are stored
        const queryString = window.location.search;
        console.log(queryString);
        // This will catch the letters in the url "?param=1" because 9 is excluded
        var firstFewChars = queryString.substring(0,9);
        // If there is no characters after the "/" Aka if there is only "localhost:3000" then
        // it will redirect the user to the url "localhost:3000/?param=-1"
        if(firstFewChars == "") {
          window.location.replace("http://localhost:3000/?param=-1");
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-16
        • 2011-01-10
        • 2020-03-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多