在哪里放置应该 运行 First ReactJs + Mobx State Tree 的代码

Where to Put Code that should run First ReactJs + Mobx State Tree

我有一些代码可以获取用户的 ipAddres。我现在在 app.js

中的 componentDidMount 中执行此操作
 async componentDidMount() {
    await eventTrackingStore.getIpAddress();
  }

所以我在我的 app.js 中做了它,因为它是我的根组件,我只想设置一次。如果用户从主页开始并在站点中导航,这会很好地工作。

但是有些页面可以直接加载(即您在浏览器中输入 url,它会直接转到该页面)。

由于 React 生命周期从最直接的组件开始,它调用一个方法,该方法期望设置 ipAddress 代码,但直到它到达 app.js

现在我可以将上面的代码放在每个方法中,但这很乏味。 reactjs 或 mbox 或 mbox 状态树中是否有某种方法会首先触发?

我可以想到两个解决方案: 您可以使用 react context

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

使用上下文在所有组件之间共享存储,如果未加载数据,则在该嵌套组件中初始化加载。

如果数据已经存在,那就拿走吧, getIpAddress 方法应该 return 一个承诺,因此如果数据已经存在,它将立即得到解决。

如果您使用 mobx-state-tree 并且您有一个全局存储,那么该全局存储可以在 afterCreate 方法

中进行 API 调用
const AppModel = types.model({
  ips: types.array(types.string)
}).actions(self => ({
  afterCreate() {
    flow(function*() {
      const ips = yield eventTrackingStore.getIpAddress();
      self.setIps(ips)
    })()

  },
  setIps(ips: string[]) {
    self.ips = ips
  }
}))

或 您可以在包装应用程序每个页面的包装 React 组件中执行相同的操作。

class App extends React.Component {
  componentDidMount() {
    eventTrackingStore.getIpAddress().then(res => {
      // set the ips into a store or any logic you want in order to pass them down to children         
    })
  }

  render() {
    return this.props.children
  }
}