【问题标题】:React Native & MobX: useContext doesn't re-render the change into the screenReact Native 和 MobX:useContext 不会将更改重新渲染到屏幕上
【发布时间】:2021-04-01 02:11:21
【问题描述】:

我一直在尝试使用 mobX 来申请 React Native 功能组件。 所以我使用这 2 个库 - mobx 和 mobx-react-lite。

我制作了一个简单的计数器应用程序,同时我还使用了上下文挂钩。 增加值后,它不适用于屏幕。但是,它出现在我的控制台上。 在我通过保存它刷新我的代码后显示更改(我没有更改代码)

我该如何解决这个问题?

App.js

import { StyleSheet, Text, View,Button } from 'react-native';
import { CounterStoreContext } from './components/CounterStore';
  
import { observer } from "mobx-react-lite";
import React, { useContext, useState } from "react";

const App = observer(() => {
  // const [count, setCount] = useState(0);
  const counterStore = useContext(CounterStoreContext)
  return (
    <View style={styles.container}>
      <Text style={styles.welcome}>Welcome</Text>
      <Text style={styles.text}>Just Press the damn button</Text>
      {/* <Text style={styles.text}>{count}</Text> */}
      {/* <Button title="Increase" onPress={()=>{setCount(count+1)}}/> */}
      <Text style={styles.text}>{counterStore.count}</Text>
      <Button title="Increase" onPress={()=>{
        counterStore.count++;
        console.log(counterStore.count)
        // setCount(counterStore.count)
      }}/>      
    </View>
  );
})

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  welcome:{
    fontSize: 20,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  text:{
    fontSize: 14,
    textAlign: 'center',
  },
});

export default App;

CounterStore.js

import { observable, observe } from "mobx";
import { createContext } from "react";

class CounterStore {
    @observable count = 0;
}

export const CounterStoreContext = createContext(new CounterStore())

【问题讨论】:

    标签: reactjs react-native react-hooks mobx use-context


    【解决方案1】:

    Since MobX 6 the @observable decorator is not enough。您还需要在构造函数中使用makeObservable / makeAutoObservable。

    class CounterStore {
        @observable count = 0;
    
        constructor() {
            makeAutoObservable(this);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-05
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 2020-03-10
      相关资源
      最近更新 更多