<链接>onClick 导致我的页面刷新 [英] &lt;Link&gt; onClick is causing my page to refresh

查看:23
本文介绍了<链接>onClick 导致我的页面刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有一个导航栏,它会在点击 props 时触发从 props 传入的函数,如下所示:

I have a navigation bar on my site that fires off a function passed in from props when they are clicked, like so:

<Filter 
  filter={this.props.params.filter}
  sub={this.props.params.sub}
  search={this.props.location.search}
  fetchData={() => this.fetchData}  />

过滤组件:

<Link to={`/r/${this.props.sub}/new/${this.props.search}`} onClick={this.props.fetchData()}>
 <span className="mdl-tabs__tab is-active">New</span>
</Link>
<Link to={`/r/${this.props.sub}/rising/${this.props.search}`} onClick={this.props.fetchData()}>
 <span className="mdl-tabs__tab is-active">Rising</span>
</Link>

获取数据:

      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);
          }
      }
    }

我遇到的问题是,只要点击这些链接标签之一,它就会刷新整个页面.虽然这有效,但我更希望页面没有刷新.我哪里出错了?

The problem I'm having is that whenever one of these link tags is clicked it refreshes the entire page. While this works I'd prefer the page didn't refresh. Where am I going wrong here?

推荐答案

所以你有了答案,也许这可以帮助其他人:你忘记在组件的构造函数中绑定事件处理程序.

So you have the answer and, maybe, that can help others: you forgot to bind the event handler in the component's constructor.

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>
    )

  }
}

这篇关于<链接>onClick 导致我的页面刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆