javascript - useEffect 没有在 Hoc 内部触发
问题描述
如果我的组件没有 HOC,它确实会触发,但现在我将组件包裹在 withSpinner Hoc 内部,但它不会触发获取开始。
const CollectionPage = (props) => {
const { isCollectionLoaded, isCollectionFetching } = props;
useEffect(() => {
props.fetchCollectionsStart();
}, []);
const { title, items } = props.collection;
return (
<div className="collection-page">
<SearchBar />
<h2 className="title">{title} </h2>
<div className="items">
{items.map((item) => (
<CollectionItem key={item.id} {...props} item={item} />
))}
</div>
</div>
);
};
const mapStateToProps = (state, ownProps) => ({
collection: selectCollection(ownProps.match.params.collectionId)(state),
isCollectionFetching: selectIsCollectionFetching(state),
isCollectionLoaded: selectIsCollectionsLoaded(state),
});
export default WithSpinner(
connect(mapStateToProps, { fetchCollectionsStart })(CollectionPage)
);
这是状态的控制台。
这是 withSpinner Hoc:
const WithSpinner = (WrappedComponent) => ({
isCollectionLoaded,
...otherProps
}) => {
return !isCollectionLoaded ? (
<SpinnerOverlay>
<SpinnerContainer />
</SpinnerOverlay>
) : (
<WrappedComponent {...otherProps} />
);
};
export default WithSpinner;
正如您从图像中看到的那样,我只看到微调器正在旋转,因为 fetchCollectionStart 没有触发,所以 redux 存储没有更新。
解决方案
isCollectionLoaded
fetchCollectionsStart
一旦调度完成并且 redux 状态更新,这将是真的(我怀疑) 。
但是你有一个问题,fetchCollectionsStart
只在 mount 阶段调度,因为默认情况下是 false 并且blocks CollectionPage
,所以永远不会发生。isCollectionLoaded
WithSpinner
CollectionPage
我建议将调度 useEffect 移动到 Spinner Hoc,考虑到您的代码结构,这很有意义。您的 hoc 可能类似于:
const WithSpinner = (WrappedComponent) => ({
isCollectionLoaded,
fetchCollectionsStart,
...otherProps
}) => {
useEffect(() => {
fetchCollectionsStart();
}, []);
return !isCollectionLoaded ? (
<SpinnerOverlay>
<SpinnerContainer />
</SpinnerOverlay>
) : (
<WrappedComponent {...otherProps} />
);
};
export default WithSpinner
推荐阅读
- php - 检查 strg 中的相同字符并从 PHP 中的下划线中删除和拆分?
- python - Python 在列表中搜索部分匹配项
- scala - Scala:如何在复制文件的函数上动态指定条件
- java - 如何将变量传递给扩展类的方法
- kotlin - 在另一个文件中实现 Kotlin 接口
- python - 确保我在每个请求中得到的推文在 twitter API 中是不同的?
- python - 正则表达式忽略特殊字符,但我需要连续四位数字,中间没有特殊字符
- date - Grails dataBinding 在默认编组 grails 日期上不起作用
- winforms - 如何使用 CefSharp winforms 接收拖动移动和拖放事件
- android - 尝试从图像视图导航到片段时应用程序崩溃