状态上不存在该属性-将React Router挂钩与TypeScript一起使用

使用react-router-dom挂钩+ TypeScript时遇到一些问题。

尝试访问某些状态属性将给出错误消息,指出该属性不存在

参考:

enter image description here

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 the state property, so:

    const location = useLocation<YourStateTypeHere>();
    

    例如:

    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!