Max*_*hke 3 javascript reactjs react-native mobx mobx-react
我在 React Native 中有一个基本的 MobX 设置,但是在 observable 更新后我的组件没有重新渲染,我似乎无法弄清楚原因。
反应原生0.56.1 ; 反应16.4.1 ; mobx 4.5.0 ; mobx 反应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;
Run Code Online (Sandbox Code Playgroud)
成分
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));
Run Code Online (Sandbox Code Playgroud)
触发器(来自不同的组件)
<TouchableOpacity
onPress={() => {
app.toggleDrawer();
// will reflect the new value
console.log(app.drawer)
}}
style={styles.toggle}
/>
Run Code Online (Sandbox Code Playgroud)
编辑:经过一些调查,没有触发重新渲染,因为我没有在render()方法中使用商店,只在componentWillReceiveProps. 这对我来说似乎很奇怪?
当我在渲染中使用 store 时,即使只分配一个变量,它也开始工作:
const x = this.props.app.drawer === false ? "false" : "true";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10612 次 |
| 最近记录: |