之前React setState後在另一個函數調用state的值沒有更新:
// init state.type = 'new'; activeMenu(type) { // type = top if (type == this.state.type) return; this.loadList(type); } loadList(type) { this.setState({ items: [], type: type }); ......... // type is top, but this.state.type still is new }
改進後的setState是這樣的:
// 使用setState的回調函數即可解決 activeMenu(type) { if (type == this.state.type) return; this.setState({ items: [], page: 1, type: type, isLoading: false, isLoadedFinished: false }, function() { this.loadList(); }); } loadList() { // 這樣我們就可以愉快及時的使用 state裏面的值 。。。 。。。 }