Reactjs <;链接>;onClick导致我的页面刷新
我的站点上有一个导航栏,当点击道具时,它会触发道具传入的函数,如下所示:Reactjs <;链接>;onClick导致我的页面刷新,reactjs,react-router,Reactjs,React Router,我的站点上有一个导航栏,当点击道具时,它会触发道具传入的函数,如下所示: <Filter filter={this.props.params.filter} sub={this.props.params.sub} search={this.props.location.search} fetchData={() => this.fetchData} /> 我遇到的问题是,每当单击其中一个链接标记时,它就会刷新整个页面。虽然这是工作,我宁愿页面没有刷新。我哪
<Filter
filter={this.props.params.filter}
sub={this.props.params.sub}
search={this.props.location.search}
fetchData={() => this.fetchData} />
我遇到的问题是,每当单击其中一个链接标记时,它就会刷新整个页面。虽然这是工作,我宁愿页面没有刷新。我哪里出了问题 因此,您得到了答案,也许这可以帮助其他人:您忘记了在组件的构造函数中绑定事件处理程序
export default YourComponent extends Component {
constructor(props) {
super(props)
this.fetchData = this.fetchData.bind(this)
}
fetchData() {
...
}
render() {
return (
...
<Link
to={`/r/${this.props.sub}/new/${this.props.search}`}
onClick={this.fetchData}
>
<span className="mdl-tabs__tab is-active">New</span>
</Link>
)
}
}
导出默认组件扩展组件{
建造师(道具){
超级(道具)
this.fetchData=this.fetchData.bind(this)
}
fetchData(){
...
}
render(){
返回(
...
新的
)
}
}
可能会删除获取数据
道具的箭头功能。相反,请使用fetchData={this.fetchData}
并检查其是否有效。我尝试过这样做,但最终从fetchData中获取无法读取未定义的
的属性“params”(我用它更新了帖子)。我使用父组件上的react路由器数据作为函数的参数。我试过做{this.fetchData.bind(this}
但似乎陷入了无限循环。您是否在组件的构造函数中绑定了fetchData
?这应该是导致此错误的原因了。啊,是的,成功了。谢谢!我刚刚遇到这种情况,我不得不说这是一种非常奇怪的意外行为。不绑定函数怎么会导致在出错之前刷新页面!无论如何,谢谢你的帮助。
fetchData() {
if (this.props.params.sub) {
if (this.props.params.filter) {
let query = `${this.props.params.sub}/${this.props.params.filter}`;
this.props.fetchList(query, this.props.location.search);
}
}
}
export default YourComponent extends Component {
constructor(props) {
super(props)
this.fetchData = this.fetchData.bind(this)
}
fetchData() {
...
}
render() {
return (
...
<Link
to={`/r/${this.props.sub}/new/${this.props.search}`}
onClick={this.fetchData}
>
<span className="mdl-tabs__tab is-active">New</span>
</Link>
)
}
}