本文介绍了单击事件刷新我的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我尝试使用以下按钮触发过滤器方法.但问题是当我点击它时,它会自动刷新我的页面.我从后端获取所需的数据,并在渲染方法之后将其存储在本地状态中.如何防止按钮引起的重新加载,以便我的过滤器方法可以正常工作?谢谢!

so I try to trigger a filter method using the following button. But problem is that when I click it, it will automatic refresh my page. I fetch my needed data from my backend and store it in a local state after the render method. How can I prevent the reload caused by the button, so my filter method can works correctly? thanks!

获取函数(在渲染函数之后使用):

fetching function(used after the render function):

  saveFetchedBeers = () =>{

        if(this.state.beers.length ===0 && this.props.beers.loading===false ){

            this.state.beers= [...this.props.beers.beer];

        }
     }

组件状态:

 state= {
        beers:[]

    }

输入&按钮:

<input ref='searchByName' type="text" placeholder="Search.." name="search"></input>
<button type="submit" onClick={() => this.getBeerByName('NL')} >Submit</button>

点击事件函数:

  getBeerByName = (input,e) =>{

         let newArray = this.state.beers.filter(function (el){
             return el.name===input;
         });

         this.state.beers = [...newArray];
     }

推荐答案

你能试试这个吗:

第一次点击事件:

<button type="submit" onClick={(e) => this.getBeerByName('NL',e)} >Submit</button>

然后像这样添加e.preventDefault()

 getBeerByName = (input,e) =>{
     e.preventDefault()
     let newArray = this.state.beers.filter(function (el){
         return el.name===input;
     });

     this.state.beers = [...newArray];
 }

或像这样将按钮类型更改为 button

or change button type to button like this

 <button type="button" onClick={() => this.getBeerByName('NL')} >Submit</button>

getBeerByName

这篇关于单击事件刷新我的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 06:45