最近在做react的一個個人項目遇到如下一個問題:我用到了react-router,比如像下面這樣(實際比這個復雜,我做了一些簡化) <Router history={hashHistory}> <Route path="/" component={IndexContainer}> <IndexRoute component={HomePage} /> <Route path="select" component={Select} /> </Route> </Router>其中HomePage組件中在constructor中會調用一些fetch等異步函數,而假設用戶快速切換到select,這個時候根據react-router的文檔,HomePage組件是會被卸載的,而這個時候之前fetch等異步函數的回調函數還沒來的及執行,因此等這些回調函數執行的時候,其實HomePage組件已經被卸載掉了,所以會報如下錯誤:warning.js:36 Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.我認為這個問題是比較常見的,不知道同道在處理這個問題上有沒有什么比較好的實踐?謝謝~
關于react的組件和路由的一個問題
收到一只叮咚
2018-10-10 15:13:04