react-redux - React - 单击按钮时无法读取未定义的属性“道具”
问题描述
我希望能够单击一个按钮并导航到网站上的另一个页面。
我尝试使用此页面中的代码,但无法使其适合我的代码。我也从另一个页面得到了这个代码。
任何帮助表示赞赏。
import React from 'react';
class Home extends React.Component{
constuctor() {
this.routeChange = this.routeChange.bind(this);
}
routeChange() {
let path = '/CreateAccount';
this.props.history.push(path);
}
render(){
return(
<div>
<p>
<button
onClick={this.routeChange}
class="btn btn-lg btn-gradient"
>
Signup
</button></p>
</div>
)
}
}
解决方案
您需要将函数绑定到正确的this
. 最简单的方法是使用 ES6 箭头函数routeChange
。如果不这样做,则this
在 routeChange 是点击的发起者,而不是组件。
箭头函数会自动绑定到this
包含实例的 。
routeChange = ()=> {
let path = '/CreateAccount';
this.props.history.push(path);
}
还有其他方法可以解决此问题,例如在构造函数中对其进行修补:
constructor( props ){
super( props );
this.routeChange = this.routeChange.bind(this);
}
...但是箭头功能更简单,更方便 imo。
推荐阅读
- archer - 如何使用 RSA Archer 中的 Web API 获取交叉引用字段中记录的 ID?
- c++ - 我正在尝试创建一个函数“InOrder”,它在二分搜索中进行中序遍历
- validation - 验证器 textarea 不起作用并始终返回 false
- c# - 即使页面尚未加载并且出现“错误:500 服务器错误”,页面加载也不会引发错误
- php - 以下是一个动态表单代码,它可以通过在行中添加来自用户的多个输入来插入数据,但我希望它在列中。我该怎么做?
- python - 预测时间序列数据中的多个特征(使用键)
- c - 不使用算术运算符减去两个数字
- highcharts - Highcharts JS v3.0.10 的 allowOverlap 属性
- php - 如何获取在 MySQL 中创建的生成外键以用于插入函数
- assembly - 我的程序集为 int 分配了两个数字并想要打印它。但是运行时,它说分段错误?