【问题标题】:How to use useHistory() hook in Class Component Type Script如何在类组件类型脚本中使用 useHistory() 钩子
【发布时间】:2021-04-13 15:44:07
【问题描述】:

你好我正在尝试使用

this.history.push({
                    pathname: `/search-results`,
                    search: `${job}$${location}`
                  }) 

在我使用 type script 的类组件中。 但是,它给了我一个错误,即“横幅”类型上不存在属性“历史”。 TS2339

我可以看到其他功能组件的例子,你可以做const history = useHistory();并使用hook中的history.push。

如何在类组件中做同样的事情?

【问题讨论】:

    标签: typescript react-router


    【解决方案1】:

    钩子并非设计用于基于类的组件。

    但是,react-router 有其他方法来支持基于类的组件,例如 withRouter higher order component

    也就是说,如果可以,请使用功能组件和挂钩。它们是未来的 React 标准。

    【讨论】:

    • 我试图按照你发送给我的链接的语法,我目前收到错误“属性'历史'不存在于类型'只读和只读'"
    • 没关系你必须定义 const { history } = this.props as any,我真的很讨厌 TS omg
    猜你喜欢
    • 2021-08-11
    • 2020-12-11
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 2020-06-06
    • 1970-01-01
    • 2020-11-01
    相关资源
    最近更新 更多