如何使用 React Hook `useWindowSize` 来初始化 MobX Store 内的窗口大小?

问题描述

我在 win() 中有 FrameItStore 函数,它返回 window.innerWidthwindow.innerHeight。但是当窗口大小改变时它并不总是更新。

FrameItStore.ts

import { makeObservable,observable,action,computed } from 'mobx'

export class FrameItStore implements IFrameItStore {
  constructor() {
    makeObservable(this,{
      win: observable,})
  }

  win(): Window {
    return {
      width: window.innerWidth,height: window.innerHeight,}
  }
}

export const config = new FrameItStore()

所以我想使用 Window Size Hook → https://www.npmjs.com/package/@react-hook/window-size获取更新的尺寸。

问题是我不知道如何使用钩子值初始化 win() 函数,因为钩子只能在 React 组件中调用

我该怎么做?

解决方法

由于您将窗口尺寸存储在 React 组件之外,如果您愿意,也可以在 React 组件之外更新它们。

示例

import { makeObservable,observable,action } from 'mobx';

export class FrameItStore implements IFrameItStore {
  win = {
    width: window.innerWidth,height: window.innerHeight
  };

  constructor() {
    makeObservable(this,{
      win: observable,updateWin: action.bound
    });
    
    // Update this.win every time the window resizes
    window.addEventListener("resize",this.updateWin);
  }

  updateWin() {
    this.win.width = window.innerWidth;
    this.win.height = window.innerHeight;
  }
  
  // If your FrameItStore won't live for the entire duration of the application,// you can call this method to remove the event listener.
  destroy() {
    window.removeEventListener("resize",this.updateWin);
  }
}