【发布时间】:2019-05-09 08:37:32
【问题描述】:
我有一个名为 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): 无法读取未定义的属性“props”
即使我尝试使用构造函数并绑定它。
如果有更好的方法在不加载页面的情况下触发搜索,我很乐意做笔记。 :)
【问题讨论】:
-
问题在于
this.handleSearch,将其与handlesearch绑定或将handlesearch定义为箭头函数。 -
@MayankShukla 我尝试了箭头功能,它确实工作得很好,谢谢!介意添加它作为答案吗? :)
标签: javascript reactjs redux