2017-09-06 49 views
0

我需要保存在本地存儲的URL,只要組件正在卸載:組件將卸載沒有得到後錨標記點擊堪稱反應

componentWillUnmount(){ 
     console.log("componentWillUnmount will call here."); 
     console.log("window.redirect.url",window.location.pathname); 

     localStorage.setItem("prevUrl",window.location.pathname); 
    } 

在另一種情況下,如果存在這樣的情況,當錨標記被點擊,上述方法不叫:

<a href="/differentpage">differentpage </a> 

我無法執行unmount方法。有什麼辦法可以執行卸載嗎?

+0

是'differentpage'是在你的SPA路線(反應路由器)或不同的頁面都在一起? –

回答

0

可以將方法綁定到你的標籤,然後在手柄方法使日誌然後重定向到您的新路徑

1

重定向到不同的頁面了SPA背景下會導致你從反應走出生命週期。就像在點擊刷新按鈕時期待經過這個循環。
你可以做什麼,是設置一個處理器到這個錨標記與e.preventDefault()停止默認行爲,然後做你的東西與狀態,並只有當你完成後,重定向窗口路徑通過e.target.href在此提供的鏈接案件。
請記住,在將窗口位置重定向到SPA外的其他頁面之後,您將失去任何狀態更新。
代碼示例:

const styles = { 
 
    fontFamily: 'sans-serif', 
 
    textAlign: 'center', 
 
}; 
 

 

 

 
class App extends React.Component { 
 

 
onClick = e => { 
 
    e.preventDefault(); 
 
    // do whatever you want with the state, but keep inmind you will lose all the data once you redirect the window out of this context (consider persistent state with local storage?) 
 
    window.location = e.target.href; 
 
} 
 

 
render(){ 
 
    return(
 
    <div style={styles}> 
 
     <a href="https://google.com" onClick={this.onClick}>click!</a> 
 
     <h2>Redirect me! {'\u2728'}</h2> 
 
    </div> 
 
); 
 
} 
 

 
} 
 

 
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="root"></div>