在 Dan Abramov 的 Egghead.io Redux 类(class)第 22 讲中,视频显示 FilterLink
组件需要显式订阅存储(通过 forceUpdate
)以便更改能够反射(reflect)在组件中。即,在SET_VISIBILITY_FILTER
之后单击过滤器后会调度 type 操作,当前过滤器 ( state.visibilityFilter
) 将更改为单击的过滤器。
我从讲座中了解到,如果我们不这样做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>
)
}
我的问题是:UI 中的结果是否包含或排除 componentDidMount
/componentWillUnmount
线条是相同的,即。单击的过滤器将变为跨度且不带下划线,另外两个将变为 <a>
并加下划线。这表明,即使没有显式订阅,来自商店的信息(本例中为 state.visibilityFilter
)也已成功传递到 <Link>
。成分。
对商店的订阅和FilterLink
中的forceUpdate也是如此。组件实现了某种在幕后重要但在 UI 中不明显的更新,还是这一步纯粹是可选的?如果用户界面中没有明显的更新,那是什么?
最佳答案
它仍然呈现的原因是因为此时代码中仍然有一个顶级呈现 store.subscribe(render);
。在视频的后面,Dan 将删除这个顶级渲染,并让类单独处理生命周期。代码更改为here .
关于javascript - FilterLink 不需要订阅即可更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36254997/