【问题标题】:Can not read history in class component无法读取类组件中的历史记录
【发布时间】:2021-09-03 13:20:52
【问题描述】:

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

【问题讨论】:

标签: javascript reactjs react-router


【解决方案1】:

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

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

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

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

export default withRouter(CentralBar);

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

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

【讨论】:

  • 感谢@brain 的深入回答。从我的下一个项目开始,我将使用 kepp 函数组件。
【解决方案2】:

你不能在类组件中使用钩子。您可以在互联网上找到许多解决方案如何解决它,但我认为这不值得。如果你真的需要在这个组件中使用钩子,请使用功能组件。在少量情况下应使用类组件进行反应。你可以在这里阅读:React functional components vs classical components

【讨论】:

  • 所以没有别的办法这不是真的..react-router 的存在时间比钩子要长..
  • 好的,我同意,但我认为在这种情况下不应该使用类组件
  • 见仁见智,不回答OP的问题。
  • 有点像,但它也是一种良好的实践规则。类组件应该在边缘情况下使用。
  • 我的主要观点是当问题是“我如何在类组件中利用历史”时,我不认为“使其成为功能组件”是一个合理的答案..
【解决方案3】:

请用 withRouter 包装你的类组件。

import { withRouter} from 'react-router-dom';
export default withRouter(CentralBar);

如果您没有安装react-router-dom 模块,请运行此命令安装此节点模块。

请让我知道它是否有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    • 2019-05-14
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    相关资源
    最近更新 更多