Home > front end >  The React after the search box input search criteria synchronous update state
The React after the search box input search criteria synchronous update state

Time:12-11

The main page & lt; The Main/& gt; :

 import the React from 'React'; 
The import Axios from 'Axios';
The import Card from '/Card';
The import '../CSS/main CSS '
The import 'font - awesome/CSS font - awesome. Min. CSS';

The class Main extends ponent {
React.Com
State={
CARDS: [],
Keyword: "'
}

ComponentDidMount () {
Enclosing retreiveData ();
}

RetreiveData ()==https://bbs.csdn.net/topics/> {
Axios. Get (` ${process. The env. REACT_APP_API_URL}/CARDS `)
Then (response=& gt; {
This. State={CARDS: the response data};
Enclosing setState (enclosing state)
})
The catch (function (error) {
The console. The log (error. The response)
})
}


HandleSearchChange=(e)=& gt; {
The console. The log (this) state) keyword)
Enclosing setState ({keyword: e. arget, value})

}


HandleSearchSubmit=(e)=& gt; {
E.p reventDefault ();
Enclosing retreiveData ();

Let newData=https://bbs.csdn.net/topics/[];
Var data=https://bbs.csdn.net/topics/this.state.cards
Data. The map ((item)=& gt; {
If (item.com panyName. IndexOf (this. State. Keyword) & gt;=0) {
NewData. Push (item)
}
});

The console. The log (newData)

Enclosing setState ({CARDS: newData}, ()=& gt; {

The console. The log (this) state) CARDS)

})

The console. The log (this) state) CARDS)
}

Render () {
Return (
<>
OnChange={this. HandleSearchChange}
/>







);
}
}
Export the default Main;


The main page pass the CARDS in the state to child components & lt; Card/& gt; .


Requirement: such as initialization data from the database when total returns 10 10 (card), only eight meet after I input the search criteria, then only need to display the eight,

Conditions, the question is: input line 49 log out for eight, but then I setState in 57 again after the log, or 10, I checked, because setState not synchronized, but you can get the latest in a callback function provided by the setState state (53 it is only eight lines of log out),

Excuse me: how to render the latest state in the setState () & lt; Card CARDS={this. State. CARDS}/& gt; Go in? So as to realize only shows the results of the eight card? Thank you

CodePudding user response:

 

Enclosing setState ({
Count: this state. The count + 1
}, ()=& gt; {
The console. The log (' complete callback function)

  • Related