简体   繁体   中英

React Router (v6) useNavigate TypeScript error: "TS2345: Argument of type 'number' is not assignable to parameter of type 'To'"

I want to use navigate() to go back in history, but TypeScript shows me an error: TS2345: Argument of type 'number' is not assignable to parameter of type 'To' .

How can I fix this issue?

const navigate = useNavigate()

useEffect(() => {
  setIsLoading(true);
  dispatch(fetchUser(userId!))
    .unwrap()
    .then(({ data }: { data: User }) => {
      setIsLoading(false);
      setUser(data);
    })
    .catch(() => navigate(-1, { replace: true }));
}, []);

Take a look at the useNavigate type declaration:

 declare function useNavigate(): NavigateFunction; interface NavigateFunction { ( to: To, options?: { replace?: boolean; state?: any } ): void; (delta: number): void; }

The interface expects either To and options arguments or a single delta argument.

By passing two args the types on the first arg no longer match and -1 isn't assignable to the To prop.

Delta navigations only navigate forward/backward through the history stack, so it doesn't make sense to tray and make it a redirect. Remove the second arg.

const navigate = useNavigate();

useEffect(() => {
  setIsLoading(true);
  dispatch(fetchUser(userId!))
    .unwrap()
    .then(({ data }: { data: User }) => {
      setIsLoading(false);
      setUser(data);
    })
    .catch(() => navigate(-1)); // <-- only delta 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