【问题标题】:ReactJS Mobx items are not updatingReactJS Mobx 项目没有更新
【发布时间】:2021-07-19 18:26:19
【问题描述】:

我正在尝试使用 MobX 构建一个扫雷游戏,我遇到的问题是我不明白为什么我的棋盘上的单元格不会更新。

这是一个包含我的代码的沙盒

https://codesandbox.io/s/epic-sun-n1dnz?file=/src/Components/CellComponent.js

在我定义的“CellComponent”中:

            <Button onClick={() => game.unveilCell(cell)}>{revealed? "2" : "?"}</Button>

所以我希望当我单击单元格时,它会显示数字 2,但只有当我等待它更新 1 分钟时,我假设我使用 MobX 观察者错误

【问题讨论】:

    标签: reactjs mobx mobx-react


    【解决方案1】:

    您需要将makeAutoObservable 调用设为Cell 构造函数中的最后一个调用:

    export default class Cell {
      value;
      x;
      y;
      revealed;
      flag;
    
      constructor(x, y) {
        this.x = x;
        this.y = y;
        this.revealed = false;
        this.flag = false;
        this.value = 0;
        // It should be in the end, after all initialisations
        makeAutoObservable(this);
      }
    
      // ...
    

    默认情况下,如果没有额外的配置,MobX 不能拾取未定义的字段并使它们可观察。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2017-03-21
      • 2017-09-05
      • 2016-01-16
      • 1970-01-01
      • 2021-12-19
      相关资源
      最近更新 更多