简体   繁体   中英

Property does not exist on state - Using React Router Hooks with TypeScript

I having some problems when using react-router-dom hooks + TypeScript.

Trying to access some state property would give an error saying that it doesn't exist

Refer to:

在此处输入图像描述

One of the workarounds that I had to do in order to continue development, was to cast it to any

 const location = useLocation() as any;

How can I pass a valid interface to the useLocation generic in order to access state properties without warnings?

  useDidMount(() => {
    if (location.state?.newTransactions) {
      scroll.scrollToBottom();
    }
  });

useLocation accepts a generic parameter that determines the type of the state property, so:

const location = useLocation<YourStateTypeHere>();

For instance:

interface LocationState {
    newTransactions?: boolean;
}

// ...
const location = useLocation<LocationState>();

// ...
useDidMount(() => {
    if (location.state?.newTransactions) {
        scroll.scrollToBottom();
    }
});

How I got there (since I hadn't used that before), in case it's useful: I know that the TypeScript bindings for most hooks implement at least one generic parameter, so when I saw that React Router's location incorporated programmer-defined state, I figured it probably accepted one. So I opened a project where I'm using React Router and TypeScript, and hovered over a useLocation in the code. Sure enough, the popup showed a generic parameter, which got applied to the state property. Result!

Didn't works for router V6

this is the declaration

export declare function useLocation(): Location;

This doesn't take any argument type

According to github issue someone suggested

interface CustomizedState {
  myState: string
}

const location = useLocation();
const state = location.state as CustomizedState; // Type Casting, then you can get the params passed via router
const { myState } = state;

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