我在 React Native 中有一个基本的 MobX 设置,但我的组件在 observable 更新后没有重新呈现,我似乎无法弄清楚为什么。
native react 0.56.1; react 16.4.1; mobx 4.5.0; mobx- react 5.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 文档,
The observer function / decorator can be used to turn ReactJS components into reactive components. It wraps the component's render function in mobx.autorun to make sure that any data that is used during the rendering of a component forces a re-rendering upon change. It is available through the separate mobx-react package.
所以你需要在observer组件的render函数中使用this.props.app.drawer
来接收来自mobx的 react 。
引用this link有关 mobx 如何以及何时使用react的更多详细信息。
关于javascript - MobX:观察到的组件在可观察到的变化后不会重新呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52807329/