click event refresh my page

2019-08-31 15:00发布

问题:

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 of the component:

 state= {
        beers:[]

    }

input & button:

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

The click event function:

  getBeerByName = (input,e) =>{

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

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

回答1:

Could you please try this :

first pass event with click :

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

then add e.preventDefault() like this

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

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

or change button type to button like this

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

without e.preventDefault in getBeerByName



回答2:

Perhaps an

e.preventDefault();

somewhere at the end of getBeerByName would do what you like, but I'm not familiar with React, so you could give it a try.