javascript - 无法读取类组件中的历史记录
问题描述
我正在尝试通过单击按钮导航到其他页面,但是通过说它会引发错误can not read property push of undefined.
我已经对history
哪些用于功能组件进行了一些研究。
我如何利用类组件中的历史记录或其他方式(反应方式)来导航其他页面。
这是我的代码。
import React, { Component } from 'react';
class CentralBar extends Component {
constructor(props){
super(props)
this.state = {
}
this.someText = this.someText.bind(this);
}
someText(){
this.props.history.push(`/login/`);
}
render() {
return (
<div className="crentralPanel">
<button type="button" class="btn btn-light " onClick={this.someText}>Click on Text</button>
</div>
);
}
}
export default CentralBar;
解决方案
history
可以在类组件中使用。您只需以与功能组件不同的方式访问它。
在函数组件中,您通常会使用useHistory
钩子。但是由于钩子是函数组件独有的,因此您必须在类中使用不同的方法。
可能最简单的方法是使用withRouter
高阶组件。您需要做的唯一更改是在顶部添加导入,然后包装导出。
import { withRouter } from 'react-router-dom';
export default withRouter(CentralBar);
这个包装器将 3 个 props 注入到组件中:history
、match
和location
.
请注意,与钩子相同的规则适用于 HOC,useHistory
因为它只是从react-router
上下文中读取的另一种方式:组件必须是Router
提供程序组件的子组件。
推荐阅读
- python - 查找日期并替换单词 - Python
- python-3.x - 如何从日期时间戳中删除字符串?
- websphere - Watson Assistant Slots:如何允许用户使用非字典实体重新输入数据?
- c# - 如何增加 AspNetCore 返回大小
- ios - 在 Swift 中在 ARImageAnchor 上播放 Youtube 视频
- azure - Terraform-Azure:授予组对 azure 资源的访问权限
- autodesk-forge - Autodesk Forge Design Automation - 打开模型时出错 - 如何绕过“模型已从远程位置传输”对话框
- powerbi - DAX 获取最后一个销售额为正的日期,无论日期行上下文
- angular - Wed Apr 08 2020 00:00:00 GMT+0530 (India Standard Time), how to get a time using mat date picker in angular
- reactjs - 在 Popover 中引用 null