【问题标题】:Adding React to an existing page and getting URL parameter inside .js将 React 添加到现有页面并在 .js 中获取 URL 参数
【发布时间】:2019-08-07 23:39:59
【问题描述】:

根据官方方法:

将 React 添加到网站https://reactjs.org/docs/add-react-to-a-website.html

我用内容创建了test.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Add React in One Minute</title>
  </head>
  <body>

    <h2>Add React in One Minute</h2>
    <p>This page demonstrates using React with no build tooling.</p>
    <p>React is loaded as a script tag.</p>

    <!-- We will put our React component inside this div. -->
    <div id="like_button_container"></div>

    <!-- Load React. -->
    <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <!-- Load our React component. -->
    <script src="test.js"></script>

  </body>
</html>

还有test.js:

'use strict';

const e = React.createElement;

class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }

  componentDidMount() {
    axios.get(`http://localhost:4000/api/v1/cars`)
      .then(result => {
        console.log(result.data[0].make);
      })
  }

  render() {
    if (this.state.liked) {
      return 'You liked this.';
    }

    return e(
      'button',
      { onClick: () => this.setState({ liked: true }) },
      'Like'
    );
  }
}

const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);

上面的代码运行良好。

我可以按 Like 按钮并查看更改,还可以使用 Axios 等库。

现在我想打开 http://localhost/test.html?param1=111&param2=222 并在 test.js 中获取这些 param1param2 变量 - 反应。那可能吗?如何做到这一点?

非常感谢

【问题讨论】:

标签: javascript html reactjs


【解决方案1】:

就像您在ComponentDidMount 中执行fetch 一样,您可以在同一lifecycle event 中检查查询参数。以link shared by @Olian04 为基础,其外观如下:

  componentDidMount() {
    const urlParams = new URLSearchParams(window.location.search);

    if (urlParams.has("param1")) {
      console.log(urlParams.get("param1"));
    } else {
      console.log("param1 was not found");
    }

    if (urlParams.has("param2")) {
      console.log(urlParams.get("param2"));
    } else {
      console.log("param2 was not found");
    }
  }

【讨论】:

  • 感谢 @Olian04 和 It'sNotMe。对我来说,这看起来很明智。稍后将对其进行测试,如果有效,则将答案标记为已回答。
  • 已确认。完美运行!
猜你喜欢
  • 2014-04-14
  • 1970-01-01
  • 2019-02-16
  • 2019-01-20
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
  • 2020-02-13
  • 2011-05-15
相关资源
最近更新 更多