ETC/트러블슈팅

[React] TypeError: window.location.href is not a function 해결

마이구미포포 2022. 7. 19. 03:39

"게시물을 수정했습니다" 라는 alert 를 띄운 후 확인 버튼을 누르면 메인 화면으로 이동하게끔 하려고했다

해당 기능을 실행하기 위해 처음에는 window.location.href 를 사용하였다

 alert("수정을 완료했습니다");
 window.location.href("http://localhost:3000/")

그랬더니 

TypeError: window.location.href is not a function

window.location.href 이 작동하지 않는다는 에러가 발생했다


해결

 

href 를 assign 으로 바꾸었더니 정상적으로 작동하였다

 alert("수정을 완료했습니다");
 window.location.assign("http://localhost:3000/")

혹은

alert("수정을 완료했습니다");
window.location.href = "http://localhost:3000/";

이렇게 작성해주었더니 확인 버튼을 누른 후 정상적으로 해당 주소로 이동하였다


그 이유는 href 는 window.location 의 method 가 아닌 속성(property)이기 때문에 함수로 호출해서는 안된다.
대신 우리는 첫번째 방법처럼 window.location.assign 이라는 method를 써야하고 
혹은 href 속성에 문자열을 할당해주어 사용해야 된다

 

 

출처 : https://bobbyhadz.com/blog/javascript-window-location-href-is-not-a-function