我在 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/