[英]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
MemoryHistory
的history
值声明为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>;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.