首页 > 解决方案 > 无法读取类组件中的历史记录

问题描述

我正在尝试通过单击按钮导航到其他页面,但是通过说它会引发错误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;

标签: javascriptreactjsreact-router

解决方案


history可以在类组件中使用。您只需以与功能组件不同的方式访问它。

在函数组件中,您通常会使用useHistory钩子。但是由于钩子是函数组件独有的,因此您必须在类中使用不同的方法。

可能最简单的方法是使用withRouter高阶组件。您需要做的唯一更改是在顶部添加导入,然后包装导出。

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

export default withRouter(CentralBar);

这个包装器将 3 个 props 注入到组件中:historymatchlocation.

请注意,与钩子相同的规则适用于 HOC,useHistory因为它只是从react-router上下文中读取的另一种方式:组件必须是Router提供程序组件的子组件。


推荐阅读