主頁面<Main />:
import React from 'react';
import Axios from 'axios';
import Card from './Card';
import '../css/main.css'
import 'font-awesome/css/font-awesome.min.css';
class Main extends React.Component{
state = {
cards:[],
keyword:'',
}
componentDidMount(){
this.retreiveData();
}
retreiveData = () =>{
Axios.get(`${process.env.REACT_APP_API_URL}/cards`)
.then(response => {
this.state = {cards: response.data};
this.setState(this.state)
})
.catch(function(error){
console.log(error.response)
})
}
handleSearchChange =(e) =>{
console.log(this.state.keyword)
this.setState({keyword: e.target.value })
}
handleSearchSubmit = (e) => {
e.preventDefault();
this.retreiveData();
let newData =[];
var data = this.state.cards
data.map((item)=>{
if(item.companyName.indexOf(this.state.keyword) >= 0){
newData.push(item)
}
});
console.log(newData)
this.setState({cards:newData},()=>{
console.log(this.state.cards)
})
console.log(this.state.cards)
}
render(){
return (
<>
<section className="jumbotron text-center">
<div className="container">
<form className="form-group" onSubmit={this.handleSearchSubmit}>
<input type="text" className="form-control" placeholder="Search this site"
onChange={this.handleSearchChange}
/>
<button className="btn btn-secondary" type="submit">
<i className="fa fa-search"></i>
</button>
</form>
</div>
</section>
<Card cards={this.state.cards}/>
</>
);
}
}
export default Main;
主頁面把state中的cards傳給子組件<Card />.
需求:好比初始化時從資料庫一共回傳10條資料(10個card),我輸入搜索條件后只有8個符合的,那么只需要顯示這8個。
問題在于:輸入條件后,49行log出來為8個,但是接下來我setState后再在57行log,出來的還是10個。 我查了下,因為setState 不是同步的,但是可以在setState 提供的回呼函式中得到最新的狀態(53行log出來確實也是只有8個)。
請問:這個setState里的最新state怎么傳到render()中的<Card cards={this.state.cards}/>中去?從而實作只顯示8個card的結果?謝謝
uj5u.com熱心網友回復:
this.setState({
count: this.state.count + 1
}, () => {
console.log('完成回呼函式')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/232875.html
標籤:JavaScript
上一篇:在網頁中如何預覽ppt檔案
下一篇:請問怎么控制谷歌瀏覽器自動填充?
