简体   繁体   English

function 中的变量未更新(使用反应挂钩)

[英]Variable is not updated inside a function (using react hooks)

I have this code我有这个代码

export const SearchWidget = memo(() => {
     . . . 
     const requestedProduct = useSelector(state => state.coverage.requestedProduct);
     . . .

    const addSearchWidget = () => {

        search = new Search({
            view: mapView,
            sources: [
                locatorSearchResource 
            ],
            container: searchContainer.current
        });

        search.on('select-result', (data) => {
            dispatch(actions.registerFoundLocation({
                 id: generateUniqueId(),
                 x: attr.x,
                 y: attr.y,
                 product: requestedProduct // <--- Always old value, 
                 // not updated from redux store!!! How to update it?
            }));
        });
    }

    useEffect(() => {
        addSearchWidget();
    }, []);

    return <div ref={searchContainer} />;

});

In dispatch call variable "requestedProduct" has always old value, which it got when it was initialised.在调度调用变量“requestedProduct”中总是有旧值,它是在初始化时得到的。

How to get current value of "requestedProduct"?如何获得“requestedProduct”的当前值?

You need to pass requestedProduct as a dependency to useEffect so that your subscriptions get the updated value.您需要将requestedProduct作为依赖项传递给 useEffect 以便您的订阅获得更新的值。

useEffect(() => {
    addSearchWidget();
}, [requestedProduct]);

or you can split creating and subscription into separate effects或者您可以将创建和订阅拆分为单独的效果

export const SearchWidget = memo(() => {
     . . . 
     const requestedProduct = useSelector(state => state.coverage.requestedProduct);
     . . .

    let search = null;
    useEffect(() => {
       search = new Search({
            view: mapView,
            sources: [
                locatorSearchResource 
            ],
            container: searchContainer.current
        });
    }, [])

    useEffect(() => {
        search.on('select-result', (data) => {
            dispatch(actions.registerFoundLocation({
                 id: generateUniqueId(),
                 x: attr.x,
                 y: attr.y,
                 product: requestedProduct
            }));
        });
    }, [requestedProduct]);

    return <div ref={searchContainer} />;

});

PS Also you must clear subscriptions when new subscription are created or on unmount PS 此外,您必须在创建新订阅或卸载时清除订阅

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

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