Window Resize - React + Redux

前端 未结 3 908
长情又很酷
长情又很酷 2020-12-23 23:22

I\'m new to Redux and I\'m wondering if anyone has some tips on best practices for handling non React events like window resize. In my research, I found this link from the o

3条回答
  •  清歌不尽
    2020-12-23 23:48

    I have a similar case where I need the window size for purposes other than responsiveness. According to this, you could also use redux-thunk:

    function listenToWindowEvent(name, mapEventToAction, filter = (e) => true) {
      return function (dispatch) {
        function handleEvent(e) {
          if (filter(e)) {
            dispatch(mapEventToAction(e));
          }
        }
    
        window.addEventListener(name, handleEvent);
    
        // note: returns a function to unsubscribe
        return () => window.removeEventListener(name, handleEvent);
      };
    }
    
    // turns DOM event into action,
    // you can define many of those
    function globalKeyPress(e) {
      return {
        type: 'GLOBAL_KEY_PRESS',
        key: e.key
      };
    }
    
    // subscribe to event
    let unlistenKeyPress = store.dispatch(listenToWindowEvent('keypress', globalKeyPress));
    // eventually unsubscribe
    unlistenKeyPress();
    

    Although in reality, if your use case is a simple one you don't even need to use a thunk function. Simply create a listener function that takes Redux dispatch as a parameter and use it to dispatch desired action. See the reference for an example. But the currently accepted answer pretty much covers this case

提交回复
热议问题