简体   繁体   English

如何使用 window.location.hash 和 Z3C797270102480CB4D13ZDA7D1 获取 url 值

[英]How to get url values with window.location.hash and reactjs?

I have this url http://localhost:3000/#/consultation/?idc=xxxd?iduser=Hyfzjg2 and I want to get the value of idc and iduser for using it on my APIs with ReactJs. I have this url http://localhost:3000/#/consultation/?idc=xxxd?iduser=Hyfzjg2 and I want to get the value of idc and iduser for using it on my APIs with ReactJs.

I try this:我试试这个:

let isInitialized = false;
const initialValues = {};
const initValues = () => {
    if (isInitialized === false) {
        const searchParams = new URLSearchParams(window.location.hash);
        const values = [
            { urlKey: "idc", stateKey: "idC" },
            { urlKey: "iduser", stateKey: "idUser" },
        ];
        values.forEach(item => {
            const urlValue = searchParams.get(item.urlKey)
            if (urlValue) {
                initialValues[item.stateKey] = urlValue;
            }
        });
        isInitialized = true;
    }
    return initialValues;
};

console.log(initValues())

When I run it, I get {} an empty value.当我运行它时,我得到{}一个空值。

How can I get the value of idc and iduser ?如何获得idciduser的值?

I think you're path isn't constructed correctly:我认为您的路径构造不正确:

If you have the path http://localhost:3000/consultation and you want to add a query string, that would be http://localhost:3000/consultation?idc=xxxx and window.location.search would be ?idc=xxxx then. If you have the path http://localhost:3000/consultation and you want to add a query string, that would be http://localhost:3000/consultation?idc=xxxx and window.location.search would be ?idc=xxxx那么?idc=xxxx

The # is a selector for an element on your page, for example #section=4, so you would typically scroll to that section. # 是页面上某个元素的选择器,例如#section=4,因此您通常会滚动到该部分。 This would look like this:这看起来像这样:

http://localhost:3000/consultation#section=4 and window.location.hash would be "#section=4" http://localhost:3000/consultation#section=4window.location.hash将是“#section=4”

I correct it and It works well:我纠正了它,它运作良好:

const  getUrlParams = (search) =>{
  let hashes = search.slice(search.indexOf('?') + 1).split('&')
  return hashes.reduce((params, hash) => {
      let [key, val] = hash.split('=')
      return Object.assign(params, {[key]: decodeURIComponent(val)})
  }, {})
}

console.log(getUrlParams(window.location.hash))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM