简体   繁体   English

React useEffect 钩子注册回调,可以访问状态

[英]React useEffect hook register callback with access to state

I´m creating a new instacne of a map component in the useEffect hook with second parameter [] so it only runs once.我正在使用第二个参数 [] 在 useEffect 钩子中创建地图组件的新实例,因此它只运行一次。

After creating the instance I want to register a callback, which is fired if the user interacts with the map.创建实例后,我想注册一个回调,如果用户与地图交互,则会触发该回调。 Inside this callback I want to access the state of my component.在此回调中,我想访问组件的状态。 How can I do this, without causing a loop?我怎样才能做到这一点,而不会造成循环? If I don´t add my state to the second parameter the state stays the same with every run of the callback (as expected), but if I add it, I cause a loop.如果我不将我的状态添加到第二个参数,则每次运行回调时状态都保持不变(如预期),但如果我添加它,则会导致循环。

export const Map = (props: any) => {
const [state, setState]: [MapState, any] = useGlobalState({
    id: 'MAP',
    initialValue: getInitialValue(initialized),
});

useEffect(() => {
    mapInstance = new mapFramework.Map(});
    mapInstance.on('move', () => {
        console.log(state);
    });
}, []);
}

You can use useRef您可以使用useRef

export const Map = (props: any) => {
const [state, setState]: [MapState, any] = useGlobalState({
    id: 'MAP',
    initialValue: getInitialValue(initialized),
});
const stateRef = useRef(state)

useEffect(()=>{
    stateRef.current = state
}, [state])

useEffect(() => {
    mapInstance = new mapFramework.Map(});
    mapInstance.on('move', () => {
        console.log(stateRef.current)
    });
}, []);
}

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

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