MobX:观察到的组件在可观察更改后不会重新渲染

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)

Ana*_*mar 6

根据 mobx 文档,

观察者函数/装饰器可用于将 ReactJS 组件转换为响应式组件。它将组件的渲染函数包装在 mobx.autorun 中,以确保在组件渲染期间使用的任何数据都会在更改时强制重新渲染。它可以通过单独的 mobx-react 包获得。

所以你需要使用this.props.app.drawerobserver组件内部的render函数来接收mobx的反应。

有关 mobx 如何以及何时做出反应的更多详细信息,请参阅此链接