javascript - MobX:观察到的组件在可观察到的变化后不会重新呈现

标签 javascript reactjs react-native mobx mobx-react

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

相关文章:

javascript - 主干 View 在没有指定预定义 el 的情况下不呈现

javascript - 在数据自动设置为 true 的情况下,在 Fotorama 中获取当前照片的完整路径

javascript - Angular : Binding objects to <select>

javascript - 我应该在前端还是后端处理 JSON,哪个更快?

javascript - 删除嵌套状态的项目会导致 DOM 中删除不正确的项目

javascript - 如何在react-router-dom中使用基于角色的身份验证?

javascript - 如何在 recharts 中按 y 轴上的固定数量分隔值

react-native - 如何在react-native中检测屏幕是否有圆角

java - 应用android.useAndroidX = true和android.enableJetifier = true修复错误会导致另一个错误

reactjs - 由于react-native中的设计,DatePickerIOS无法工作