首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React Native & MobX: useContext不会将更改重新呈现到屏幕上

React Native & MobX: useContext不会将更改重新呈现到屏幕上
EN

Stack Overflow用户
提问于 2021-04-01 10:11:21
回答 1查看 181关注 0票数 1

我一直在尝试使用mobX来应用于React Native Functional组件。所以我使用了这两个库- mobx & mobx-react-lite。

我做了一个简单的计数器应用程序,我也与此useContext挂钩。增加该值后,它不会在屏幕上应用。然而,它出现在我的控制台上。在我通过保存刷新代码(我没有更改代码)之后,更改就会显示出来。

我该如何解决这个问题?

App.js

代码语言:javascript
复制
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

代码语言:javascript
复制
import { observable, observe } from "mobx";
import { createContext } from "react";

class CounterStore {
    @observable count = 0;
}

export const CounterStoreContext = createContext(new CounterStore())
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-02 00:48:14

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

代码语言:javascript
复制
class CounterStore {
    @observable count = 0;

    constructor() {
        makeAutoObservable(this);
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66897589

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档