【问题标题】:URL query parameters returns null even when parameter is seted即使设置了参数,URL 查询参数也会返回 null
【发布时间】:2021-06-05 08:28:51
【问题描述】:

我有一个带有反应路由器和动态 URL 的反应应用程序。而且我还有 2 个 GET 参数,例如 /?name=something&date=2021,而名称参数工作正常 date 出于某种原因总是返回 null。 我用 onSubmit 在表单中设置参数

function submitAction(e) {
  e.preventDefault();
  props.onChange(search, selectedDate);
  const currUrl = new URL(window.location.href);
  currUrl.searchParams.set("date", format(selectedDate, "yyyy"));
  currUrl.searchParams.set("name", search);
  window.history.pushState({}, "", currUrl);
  setSearch("");
}

并用useEffect()react hook获取参数

  useEffect(() => {
const params = new URLSearchParams(window.location.href);
const date = params.get("date");
const name = params.get("name");
console.log(name);
console.log(date);  //this always returns null
if (name) {
  setFilter(name);
}
if (date) {
  setDate(new Date(date));
}}, []);

所以我的查询字符串发生了变化并且可以正常工作,但是我的第二个 URL 参数不工作 查询字符串看起来像http%3A%2F%2Flocalhost%3A3000%2F%3Fdate=2018&name=

【问题讨论】:

  • 在 submitAction 中放一个console.log(selectedDate); 来测试值。还有,format函数的代码是什么?
  • console.log(selectedDate) 返回Date Tue Jun 05 2018 11:38:33 GMT+0300
  • format 是 date-fns 包中的一个函数,用于将 Date() 对象解析为所需格式
  • console.log(format(selectedDate, 'yyyy')); 输出什么?
  • for Date Tue Jun 05 2018 11:38:33 GMT+0300 console.log(format(selectedDate, 'yyyy')) 返回 2018

标签: javascript reactjs url


【解决方案1】:

URLSearchParams 构造函数不解析完整的 URL,只解析查询字符串。

改变

const params = new URLSearchParams(window.location.href);

const params = new URLSearchParams(window.location.search);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-08
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    相关资源
    最近更新 更多