简体   繁体   中英

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 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 ?

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.

The # is a selector for an element on your page, for example #section=4, so you would typically scroll to that section. This would look like this:

http://localhost:3000/consultation#section=4 and window.location.hash would be "#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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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