简体   繁体   中英

In React, replacing URL with an identical value causes infinite loop

      if (new_path !== window.location.pathname + window.location.search) {
        history.replace({
          pathname: new_path,
          search: "",
        });
      }

EDITED:

new_path is just a string. Without the if statement, the above code will cause infinite loop.

Is that expected behavior?

It will only cause an infinite loop if

new_path is different than window.location.pathname + window.location.search .

If you want to check its values, try to preserve logs on chrome developer tools and then start your app. That way you can see why it is generating an infinite loop.

If new_path is a state in your app it should be inside {}

pathname: {new_path}

The "if" condition is the wrong one.

if (new_path !== window.location.pathname + window.location.search) {}

This will be true always and history.replace will run again.

so the solution is

if (new_path[<your key>] !== window.location[<your key>]) {}

If you meant to be the new_path is a string, you need to check what is the new_path value

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