在Dan Abramov的egghead.io Redux課程22講座中,視頻表示FilterLink
組件需要明確訂閱商店(通過forceUpdate
)以便將更改反映到組件。也就是說,在單擊過濾器後調度SET_VISIBILITY_FILTER
類型的操作後,當前過濾器(state.visibilityFilter
)將變爲點擊過的一個過濾器。FilterLink不需要訂閱更新
我從演講的理解是,如果我們沒有subscribe
並做了forceUpdate
,對過濾器的格式不會改變,因爲信息沒有被傳播到FilterLink
形式存儲,然後下到Link
。
但是,當我將componentDidMount
和componentWillUnmount
中的行刪除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>
)
}
我的問題是:是否包括或不包括componentDidMount
/componentWillUnmount
線是相同的即在用戶界面中的結果。點擊過濾器將變爲範圍並且不加下劃線,其他兩個將變爲<a>
並加下劃線。這表明,即使沒有明確的訂閱,來自商店的信息(在這種情況下爲state.visibilityFilter
)已成功傳遞到<Link>
組件。
因此,商店訂閱和FilterLink
組件中的forceUpdate實現了某種在幕後很重要的更新,並且在用戶界面中不明顯,或者此步驟純粹是可選的?如果UI中有一個不明顯的更新,它是什麼?