如何跟踪 componentDidUpdate 中的 mobx 全局存储更改

How to track mobx global store changes in componentDidUpdate

我正在玩 react + mobx + mobx-react 库。我创建了 mobx 商店来存储应用程序设置 (appSettingsStore)。我的 React 应用程序有 2 个组件,即 AppHeaderAppBody。 AppHeader 有下拉列表,onChange 值存储在 mobx 存储中。在我的 AppBody 组件中,我调用 API 来获取 componentDidMount 中的数据。 AppBody 组件包裹在路由器周围,随着 AppHeader 下拉列表中值的变化,不同的页面有不同的 API 调用。

每次更改下拉列表中的选择时,我都想在 AppBody 组件中调用 API。有什么方法可以跟踪 componentDidUpdate 中我的 mobx 商店 appSettingsStore 的变化吗?

我创建了 codesandbox 以供参考 - https://codesandbox.io/s/gracious-flower-vu1js?file=/src/App.tsx

App.tsx

export default function App() {
  return (
    <React.Fragment>
      <AppHeader />
      <Router>
        <Switch>
          <Route to="/" component={AppBody} exact />
        </Switch>
      </Router>
    </React.Fragment>
  );
}

AppSettingsStore.ts(用于存储全局应用程序设置的 Mobx 商店)

import { observable, action } from "mobx";

export class AppSettingsStore {
  @observable
  settings = "";

  get getAppSettings() {
    return this.settings;
  }

  @action
  setAppSettings(settings: string) {
    this.settings = settings;
  }
}

export const appSettingsStore = new AppSettingsStore();

Header.tsx

@observer
export class AppHeader extends Component {
  render() {
    return (
      <div>
        My React App header component
        <select
          onChange={e => appSettingsStore.setAppSettings(e.target.value)}
          style={{ width: 200, float: "right" }}
          value={appSettingsStore.getAppSettings}
        >
          <option value="" />
          <option value="one">One</option>
          <option value="two">Two</option>
          <option value="three">Three</option>
        </select>
      </div>
    );
  }
}

Body.tsx

@observer
export class AppBody extends Component {
  async componentDidMount() {
    // API calls
  }

  async componentDidUpdate() {
    // Check if mobx store value is different
    // from previous then call API otherwise ignore
    console.log(appSettingsStore.getAppSettings);
    // API calls
  }

  render() {
    return <div style={{ padding: "5rem" }}>This is App body component</div>;
  }
}

非常感谢您的帮助。

听音设置必须要用reaction,像下一个 已更新 (sandbox)

import { reaction, ... } from 'mobx';

@observer
export class AppBody extends Component {
  constructor(props) {
    super(props);

    this.reactions = []; // it needs to dispose reaction on unmount
  }

  async componentDidMount() {
    // API calls

    this.reactions = [
      reaction(
        () => appSettingsStore.settings,
        this.handleSettingsUpdates
      )
    ]
  }

  componentWillUnmount() {
    this.reactions.forEach((dispose) => dispose());
  }

  handleSettingsUpdates = (newSettings) => {
    console.log('newSettings = ', newSettings);
  }

  render() {
    return <div style={{ padding: "5rem" }}>This is App body component</div>;
  }
}