使用react-router-dom挂钩+ TypeScript时遇到一些问题。
尝试访问某些状态属性将给出错误消息,指出该属性不存在
参考:
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;
如何在不发出警告的情况下将有效接口传递给useLocation泛型,以访问状态属性?
useDidMount(() => {
if (location.state?.newTransactions) {
scroll.scrollToBottom();
}
});
useLocation
accepts a generic parameter that determines the type of thestate
property, so:例如:
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 auseLocation
in the code. Sure enough, the popup showed a generic parameter, which got applied to thestate
property. Result!