2017-05-03 70 views
2

我有組件搜索功能SearchArticle(),它正確使用this.state.search在組件掛載後顯示DEFAULT值(控制檯顯示正在搜索...:DEFAULT)。但是,當我更新this.state.search與handleKeyPress(E)他們相同的功能SearchArticle()它更新到e.target值之前使用上一個狀態(控制檯顯示搜索...:再次DEFAULT)。不知道如何解決它。如何通過React中的事件處理程序更新和使用狀態

class Searcher extends Component { 

    constructor(props) { 
     super(props); 
     this.state = { 
      article: [], search: "DEFAULT" 
     }; 
    } 

    searchArticle() { 
     console.log('Searching...: ', this.state.search)         
    } 

    handleKeyPress = (e) => { 
     if (e.key === 'Enter') {        
      this.setState({search: e.target.value}); 
      this.searchArticle(); 
     } 
    } 

    componentDidMount() { 
     this.searchArticle();  
    } 

    render() { 
     return (
      <div className="row"> 
      Search: <input onKeyPress={this.handleKeyPress} type="text" /> 
      </div>    
     ) 
    } 

} 

回答

4

最有可能在console.log執行時狀態沒有更新。這是因爲setState()是異步的。

那麼試試這個來代替:

handleKeyPress = (e) => { 
    if (e.key === 'Enter') {        
    this.setState({search: e.target.value},() => { 
     this.searchArticle(); 
    });  
    } 
} 

我搬到你searchArticle()setState()回調。這將保證其執行之後的狀態已實際更新。


瞭解更多關於setState()here

setState()視爲請求而不是立即更新組件的命令。爲了獲得更好的感知性能,React可能會延遲它,然後一次更新幾個組件。 React不保證立即應用狀態更改。

setState()並不總是立即更新組件。它可能會批處理或推遲更新,直到稍後。這使得在撥打setState()之後立即閱讀this.state是一個潛在的缺陷。相反,使用componentDidUpdatesetState回調(setState(updater, callback)),其中任何一個保證在應用更新後觸發。

[...]

setState()第二個參數是一次的setState完成並且部件被重新呈現將要執行的可選的callback函數。

相關問題