如何在componentDidUpdate中跟踪mobx全局商店的变化。

问题描述 投票:0回答:1

我在玩 react + mobx + mobx-react 库。我已经创建了mobx商店来存储应用程序设置(appSettingsStore). 我的react应用有2个组件,即AppHeader & AppBody. AppHeader有下拉菜单,onChange的值存储在mobx商店中。在我的AppBody组件中,我调用API来获取数据。componentDidMount. AppBody组件被包裹在路由器上,不同的页面有不同的API调用,因为值的变化。AppHeader 下拉菜单。

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

我已经创建了codesandbox,供大家参考- https:/codesandbox.iosgracious-flower-vu1js?file=srcApp.tsx。

App.tsx

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

AppSetStingsStore.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>;
  }
}

我将感谢你的帮助。

javascript reactjs mobx mobx-react
1个回答
1
投票

你必须使用react来进行监听设置,比如nextupdated (沙盒)

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>;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.