javascript - React Native、MobX 和生命周期

标签 javascript react-native lifecycle mobx

我在 React Native 中使用 MobX,到目前为止我真的很精简它。 当 Mobx Store 中的状态发生变化时,是否有一些生命周期或方法来调用函数?

最佳答案

componentWillReceiveProps 可以在组件级别使用。例如,观察者容器会通过 props 通知实际组件(TypeScript 中的虚构用例):

@inject('notificationStore')
@observer
class SomeContainer extends Component<Props> {
  ...

  public render(): JSX.Element {
    <Notification
      message={this.props.notificationStore.message}
      ...
    />
  }
}

在通知中:

class Notification extends PureComponent<Props> {
  ...
  public componentWillReceiveProps(nextProps: any): void {
    Alert.alert('message', nextProps.message);
  }
}

现在,当您改变 notificationStore.message 时,例如。 'Hello world',它将由 Notification 组件显示。

如果您想要更直接的方法,那么您只需将组件注入(inject)存储并观察变化。基本上你的 TypeScript 界面应该是这样的:

interface Props {
  notificationStore?: any;
  ...
}

如您所见,store 始终被视为 prop,这意味着突变将触发 componentWillReceiveProps 生命周期事件。

希望我已经解释清楚了。

关于javascript - React Native、MobX 和生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47347576/

相关文章:

php 数组到基于按钮单击的 javascript

javascript - 我怎样才能得到JavaScript中的负责任的URL的长度

react-native - react 原生中从右到左

java - 如何强制 Maven 在站点生命周期之前运行构建生命周期?

java - Kotlin lang 上 android.arch.lifecycle 的 Android 致命异常

javascript - 在 Web 动画 API 中堆叠/添加/复合/累积多个转换=翻译动画

java - 如何使用 <s :property/> tag 执行 JavaScript

node.js - UseState() 函数中出现错误 - 预期;

android - React Native ScrollView 与成长中的 child

java - 具有相同名称的私有(private)回调方法