2016-03-28 30 views
0

在Dan Abramov的egghead.io Redux課程22講座中,視頻表示FilterLink組件需要明確訂閱商店(通過forceUpdate)以便將更改反映到組件。也就是說,在單擊過濾器後調度SET_VISIBILITY_FILTER類型的操作後,當前過濾器(state.visibilityFilter)將變爲點擊過的一個過濾器。FilterLink不需要訂閱更新

我從演講的理解是,如果我們沒有subscribe並做了forceUpdate,對過濾器的格式不會改變,因爲信息沒有被傳播到FilterLink形式存儲,然後下到Link

但是,當我將componentDidMountcomponentWillUnmount中的行刪除FilterLink組件時,該應用程序運行正常,似乎信息仍在傳播,即使沒有明確強制更新存儲。

class FilterLink extends Component { 



     componentDidMount() { 
     this.unsubscribe = store.subscribe(() => 
     this.forceUpdate() 
    ); 
    } 

    componentWillUnmount() { 
     this.unsubscribe(); 
    } 


    render() { 

     const { 
     filter, 
     children, 
     } = this.props; 
     const state = store.getState(); 
     return (
     <Link 
     active = {filter === state.visibilityFilter} 
     onClick = {() => store.dispatch({ 
      type: 'SET_VISIBILITY_FILTER', 
      filter: filter, 
     })} 


     > {children}</Link> 
    ) 
    } 

    } 

從下面的代碼中,我們看到,只有主用鏈路具有<span>(即不加下劃線)和非有源濾波器應低於他們下劃線出現。

const Link = ({ 
    active, 
    children, 
    onClick, 
    }) => { 

if (active) { 
    return (
    <span> 
    {children} 
    </span> 
) 
} 
else return (
    <a href='#' onClick = { e => { 
     e.preventDefault(); 
     onClick() 
    } 
    } 

    >{children}</a> 
) 
} 

enter image description here enter image description here enter image description here

我的問題是:是否包括或不包括componentDidMount/componentWillUnmount線是相同的即在用戶界面中的結果。點擊過濾器將變爲範圍並且不加下劃線,其他兩個將變爲<a>並加下劃線。這表明,即使沒有明確的訂閱,來自商店的信息(在這種情況下爲state.visibilityFilter)已成功傳遞到<Link>組件。

因此,商店訂閱和FilterLink組件中的forceUpdate實現了某種在幕後很重要的更新,並且在用戶界面中不明顯,或者此步驟純粹是可選的?如果UI中有一個不明顯的更新,它是什麼?

回答

1

它仍然呈現的原因是因爲代碼中此時仍然存在頂級渲染store.subscribe(render);。在後面的視頻中,Dan會刪除這個頂層渲染,並讓這些類完全處理生命週期。代碼更改爲here