首页 > 解决方案 > 在 React 类组件中更改 URL onClick 或 onSubmit 的最佳方法是什么?

问题描述

我知道 React 中功能组件的 useHistory 钩子,但是在我的应用程序中,我有一个类组件,我希望它能够更改 URL。

基于类的组件是否有等效的 useHistory ?如果不是,那么完成此任务的公认方法是什么?

标签: reactjsreact-routerreact-router-v4browser-history

解决方案


可能你需要这样的东西:

import { withRouter } from 'react-router-dom'    

export const Component = withRouter(({ history, location }) =>{

})

class Comp extends Component {
    render(){
        const { location, history } = this.props
    }
}
export default withRouter(Comp)

这里回答了一个类似的问题:https ://stackoverflow.com/a/58122270/7306148


推荐阅读