>我在 React Native 中有一个基本的 MobX 设置,但我的组件在可观察量更新后没有重新渲染,我似乎无法弄清楚为什么。
React-native 0.56.1; react16.4.1; mobx 4.5.0; mobx-react5.2.8
商店
class AppStore {
drawer = false;
toggleDrawer = () => {
this.drawer = !this.drawer;
}
}
decorate(AppStore, {
drawer: observable,
toggleDrawer: action
});
const app = new AppStore();
export default app;
元件
class _AppLayout extends React.Component {
constructor(props) {
super(props);
this.state = {
drawerAnimation: new Animated.Value(0)
};
}
UNSAFE_componentWillReceiveProps(nextProps) {
console.log('will not get called');
if (this.props.app.drawer !== nextProps.app.drawer) {
Animated.timing(this.state.drawerAnimation, {
toValue: nextProps.app.drawer === true ? 1 : 0,
duration: 500
}).start();
}
}
render() {
console.log("will only be called on first render");
const translateX = this.state.drawerAnimation.interpolate({
inputRange: [0, 1],
outputRange: [0, -(width - 50)]
});
return (
<Animated.View style={[styles.app, { transform: [{ translateX }] }]}>
<View style={styles.appContent}>
<RouterSwitch />
</View>
<View style={styles.appDrawer} />
</Animated.View>
);
}
}
const AppLayout = inject("app")(observer(_AppLayout));
触发器(来自不同的组件(
<TouchableOpacity
onPress={() => {
app.toggleDrawer();
// will reflect the new value
console.log(app.drawer)
}}
style={styles.toggle}
/>
编辑: 经过一些调查,没有触发重新渲染,因为我没有在render()
方法中使用存储,只在componentWillReceiveProps
中使用。这对我来说似乎很奇怪?
当我在渲染中使用存储时,即使只是分配一个变量,它也会开始工作:
const x = this.props.app.drawer === false ? "false" : "true";
根据 mobx 文档,
观察器函数/装饰器可用于将 ReactJS 组件转换为响应式组件。它将组件的呈现函数包装在 mobx.autorun 中,以确保在呈现组件期间使用的任何数据都会在更改时强制重新呈现。它可以通过单独的 mobx-react 包获得。
因此,您需要使用观察者组件的渲染函数内部this.props.app.drawer
来接收来自 mobx 的反应。
有关 mobx 如何以及何时做出反应的更多详细信息,请参阅此链接。
您需要在组件上使用observer
frommobx-react
,使用装饰器也是最佳实践。还要确保在根组件上使用提供程序
商店
class AppStore {
@observable drawer = false;
@action toggleDrawer = () => {
this.drawer = !this.drawer;
console.log(this.drawer)
}
}
元件
const app = new AppStore();
export default app;
@observer
class AppLayout extends React.Component {
constructor(props) {
super(props);
this.state = {
drawerAnimation: new Animated.Value(0)
};
}
UNSAFE_componentWillReceiveProps(nextProps) {
console.log('will not get called');
if (this.props.app.drawer !== nextProps.app.drawer) {
Animated.timing(this.state.drawerAnimation, {
toValue: nextProps.app.drawer === true ? 1 : 0,
duration: 500
}).start();
}
}
render() {
console.log("will only be called on first render");
const translateX = this.state.drawerAnimation.interpolate({
inputRange: [0, 1],
outputRange: [0, -(width - 50)]
});
return (
<Provider app={app}>
<Animated.View style={[styles.app, { transform: [{ translateX }] }]}>
<View style={styles.appContent}>
<RouterSwitch />
</View>
<View style={styles.appDrawer} />
</Animated.View>
</Provider>
);
}
}
触发
<TouchableOpacity
onPress={() => {
app.toggleDrawer();
// will reflect the new value
console.log(app.drawer)
}}
style={styles.toggle}
/>