变量不会在函数内部更新(使用 react 钩子)



我有这个代码

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

在调度调用变量"requestProduct"中,它总是具有旧值,它在初始化时得到。

如何获取"请求产品"的当前值?

需要将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} />;
});

附言此外,还必须在创建新订阅或卸载时清除订阅

相关内容

  • 没有找到相关文章

最新更新