简体   繁体   English

“历史”类型上不存在属性“索引”<unknown> &#39; 使用内存路由器

[英]Property 'index' does not exist on type 'History<unknown>' using MemoryRouter

I'm trying to access the property index from history object when using MemoryRouter , but it generates a Typescript error, since the index attribute is not in the type definitions of history object.使用MemoryRouter时,我试图从历史对象访问属性index ,但它会生成 Typescript 错误,因为index属性不在history对象的类型定义中。 Here is the error:这是错误:

Property 'index' does not exist on type 'History<unknown>'.

But the index attribute is there when I console.log the history object.但是当我 console.log 历史对象时index属性就在那里。 Here is an example of history's state:这是历史状态的示例:

action: "POP"
block: ƒ block(prompt)
canGo: ƒ canGo(n)
createHref: ƒ createPath(location)
entries: (5) [{…}, {…}, {…}, {…}, {…}]
go: ƒ go(n)
goBack: ƒ goBack()
goForward: ƒ goForward()
index: 0
length: 5
listen: ƒ listen(listener)
location: {pathname: '/app', search: '', hash: '', state: undefined, key: 't5skrl'}
push: ƒ push(path, state)
replace: ƒ replace(path, state)

I know that it is possible to provide a type for useHistory hook, but i've tried doing like useHistory<{ index: number }>() and it didn't solve the problem.我知道可以为useHistory钩子提供一种类型,但我尝试过类似useHistory<{ index: number }>()并没有解决问题。

Code example:代码示例:

import { MemoryRouter, Route, Switch, useHistory } from "react-router-dom"

const App = () => {
  return (
    <MemoryRouter>
      <Switch>
        <Route path="/" component={Page} />
      </Switch>
    </MemoryRouter>
  )
}

const Page = () => {
  const history = useHistory()
  console.log(history.index)

  return (
    <div>Page</div>
  )
}

Import MemoryHistory from the history package and declare the returned history value from useHistory as a MemoryHistory object.history包中导入MemoryHistory MemoryHistoryhistory值声明为useHistory对象。

Example:例子:

import { Switch, Route, useHistory } from "react-router-dom";
import { MemoryHistory } from "history";

const Page = () => {
  const history = useHistory() as MemoryHistory;
  console.log(history.index);

  return <div>Page</div>;
};

编辑 property-index-does-not-exist-on-type-historyunknown-using-memoryrouter (forked)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM