简体   繁体   English

当依赖项更改时,React useEffect hook 不会触发

[英]React useEffect hook doesn't trigger when a dependency changes

I have this useEffect hook我有这个 useEffect 钩子

useEffect(() => {
    console.log('mark useEffect', compatibleProducts);
    if (Object.keys(compatibleProducts.rims).length === 0
            && Object.keys(compatibleProducts.tires).length === 0) return;

}, [compatibleProducts,...]);

在此处输入图像描述

As you can see in the picture the state with the (COMPATIBLE_PRODUCTS) changes at the last line.正如您在图片中看到的,state 在最后一行更改了 (COMPATIBLE_PRODUCTS)。 In the state I check, indeed values are added, but the useEffect hook doesn't trigger again.在我检查的 state 中,确实添加了值,但 useEffect 挂钩不会再次触发。

Any reason why it does this?有什么理由这样做吗?

State before: State 之前: 在此处输入图像描述 State after: State 之后: 在此处输入图像描述

Reducer action:减速机作用: 在此处输入图像描述

You should try in reducer你应该试试减速器

case TYPE.COMPATIBLE_PRODUCTS.SUCCESS:
            return {
                ...state,
                compatibleProducts: {
                    ...state.compatibleProducts,
                    ...action.compatibleProducts,
                    timespan: + new Date()
                }
            }

in your component在你的组件中

useEffect(() => {
    ...
}, [compatibleProducts.timespan]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM