【问题标题】:URLSearchParams is not a constructor in ReactJSURLSearchParams 不是 ReactJS 中的构造函数
【发布时间】:2019-12-29 19:35:24
【问题描述】:

我在使用URLSearchParams时遇到了这个错误

TypeError: url__WEBPACK_IMPORTED_MODULE_2__.URLSearchParams 不是构造函数

我是这样称呼的:

componentDidMount() {
    const query = new URLSearchParams(this.props.location.search); // <- ERORR
    const ingredients = {};
    for (let param in query.entries()) {
        // ['salad', '1']
        ingredients[param[0]] = +param[1];
    }
    this.setState({ingredients : ingredients});
}

我的 ReactJS 项目详情:

"dependencies": {
"axios": "^0.19.0",
"prop-types": "^15.7.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-router-dom": "^5.0.1",
"react-scripts": "3.0.1"
},

【问题讨论】:

  • 我认为你不需要URLSearchParams,你可以直接使用this.props.location.match.params获取参数。检查这个 - freecodecamp.org/news/…
  • 认为这是因为 webpack 没有被配置为目标浏览器。
  • 如何定位浏览器?在哪里可以找到此配置?

标签: javascript reactjs react-router


【解决方案1】:

当 react import UrlSearchParams from 'url' 时会发生这种情况 所以你必须删除它并尝试它。一定会成功的。

【讨论】:

  • 这是对的,import { URLSearchParams } from "url" 导致了这个问题,删除它后解决了我的问题。
【解决方案2】:

我认为你应该从react-router-dom 加载location。这将允许您从路由器访问位置和 url 参数。请注意同时传递您的用户,以防您的应用需要对组件本身进行身份验证..

我不确定search 会告诉你真相,但你应该可以通过 |react-router-dom` 轻松获得位置

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2013-12-25
    • 2021-01-11
    • 2015-12-04
    相关资源
    最近更新 更多