javascript - (TypeError):无法读取未定义的属性“道具”
问题描述
我有一个名为 Search 的组件负责任何搜索
代码:
class Search extends Component {
state = {
searchResult: []
}
async componentDidMount() {
await this.props.searchAssets(this.props.match.params.name);
this.handleState();
}
handleState() {
this.setState({ searchResult: this.props.searchResult });
}
async handleSearch(e) {
e.preventDefault();
await this.props.searchAssets(e.target.q.value);
this.handleState()
}
render() {
return (
<div className="content-block">
<form onSubmit={this.handleSearch} className="search-form">
<button>بحـث</button>
<input type="text" defaultValue={this.props.match.params.name} name="q" placeholder="Est: Game of thrones, Vikings or Deadpool" />
</form>
<div className="display-latest">
***the div where search results are shown***
</div>
</div>
)
}
}
它工作得非常好,直到我尝试在页面上添加另一个搜索表单,我试图让它重用来自 redux 的操作,但它一直给我这个错误
(TypeError):无法读取未定义的属性“道具”
即使我尝试使用构造函数并绑定它。
另外,如果有更好的方法可以在不加载页面的情况下触发搜索,我很乐意做笔记。:)
解决方案
该函数handleState
并handleSearch
缺少对 this 的引用。您可以通过以下两种方式获得参考:
- 如果您使用
transform-class-properties
的似乎是您的情况,您可以将函数更改为箭头函数。 您必须使用以下方式在构造函数中绑定函数:
this.handleState = this.handleState.bind(this);
这些中的任何一个都应该解决这里的问题。
推荐阅读
- python - 如何使用熊猫从字符串中删除小数点
- node.js - winston 'handleExceptions: true' 记录两次
- maven - 无法执行 SonarQube:无法从服务器获取引导索引:
- javascript - 如何以 html 格式分配 javascript 变量?
- html - WordPress 125% 重复小部件/更改媒体断点
- javascript - 如何使用 iframe 中的元素创建 if 语句?
- dart - 在匿名函数 Dart.js 中引用 this
- java - 显示偶数后跟所有奇数
- azure - 条件访问会阻止另一个应用程序中的 onedrive
- mysql - 风帆模型协会