变量未在函数内部更新(使用react挂钩)

时间:2019-10-16 08:44:08

标签: reactjs callback react-hooks

我有这个代码

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} />;

});

在调度调用变量“ requestedProduct”中始终具有旧值,该值是在初始化时获得的。

如何获取“ requestedProduct”的当前值?

1 个答案:

答案 0 :(得分:1)

您需要传递requestedProduct作为useEffect的依赖项,以便您的订阅获得更新的值。

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

或者您可以将创建和订阅分成单独的效果

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} />;

});

P.S。另外,在创建新订阅或取消订阅时,您还必须清除订阅