【问题标题】:React Router typescript Property 'redirectUrl' does not exist on type '{}'反应路由器打字稿属性'redirectUrl'在类型'{}'上不存在
【发布时间】:2021-01-07 17:53:13
【问题描述】:

我想通过 history.push 与分页相关的部分 url 发送状态到登录页面。 但是我不知道如何在 Login 中输入它,所以 typescript 会理解 state 到底包含什么。

我收到的错误:

Property 'redirectUrl' does not exist on type '{}'
if (!isAuthorized) {
   history.push({ pathname: AppRoute.login, state: { redirectUrl: 'page=2' } });

  return;
}

登录页面

const history = useHistory();
const redirectState = history?.location?.state;

if (isAuthorized) {
    history.push({ pathname: AppRoute.home, search: redirectState?.redirectUrl })

    return;
}

【问题讨论】:

    标签: reactjs typescript react-router react-router-dom


    【解决方案1】:

    您收到该错误是因为您没有正确调用history.push()。它接受一个路径和一个状态,作为两个单独的参数:

    history.push(AppRoute.login, { redirectUrl: 'page=2' });
    

    然后在另一方面,您可以输入您的 useLocation 调用,将它传递给您期望的状态类型。

    function LoginPage() {
      const location = useLocation<{ redirectUrl: string }>()
      console.log(location.state.redirectUrl) // typed as: { redirectUrl: string }
    }
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-18
      • 2020-11-10
      • 1970-01-01
      • 2022-11-04
      • 2017-03-02
      • 2021-09-07
      • 2019-05-05
      • 2017-10-30
      相关资源
      最近更新 更多