简单的MobX可观察而不是渲染

时间:2020-05-28 10:13:03

标签: reactjs mobx mobx-react

我有一个带有MobX @observer批注的简单React类和一个简单的数据结构(带有@observable data = { .. }的注释。一个动作会更新此结构,但会渲染。

以下是该类的源代码:-

import React, {Component, Fragment} from 'react';
import {observer} from "mobx-react";
import {observable} from "mobx";
import {withRouter} from 'react-router-dom';

@observer
@withRouter
class UpdateDetailsForm extends Component {

  constructor(props) {
    super(props);
    this.onClick = this.onClick.bind(this);
  }

  @observable data = {
    error: ""
  };

  onClick () {
    this.data.error = "error has occurred";
    console.log("Something has happened!");   // testing purposes
  }

  render() {
    return (
      <div>
        <div className="red">[ {this.data.error} ]</div>
        <input type="button" value="Click Me!" onClick={this.onClick} />
      </div>      
    );
  }

}

但是,当我单击按钮时,控制台将显示...

Something has happened!

...证明data的状态已突变,但HTML不会更新。

2 个答案:

答案 0 :(得分:0)

只需弄清楚!这是类批注的顺序很重要,即

@withRouter
@observer
class UpdateDetailsForm extends Component {

...

这行得通!

但是,当@withRouter是最接近class UpdateDetailsForm的注释时,它将失败。

也在MobX文档中找到了此内容-https://mobx.js.org/best/pitfalls.html

_@inject('store')之前的

@observer将导致MobX无法触发_

@inject注释也是如此。

答案 1 :(得分:0)

只需查看您的 mobx 版本。在 mobx 版本 6 之前,这将起作用。从版本 6 开始,您需要在构造函数中添加一个额外的 makeObservable(this)

This 是官方帖子。

<块引用>

MobX 6 之前的版本不需要构造函数中的 makeObservable(this) 调用,但是因为它使装饰器的实现更简单和更兼容,所以现在需要。这指示 MobX 根据装饰器中的信息使实例可观察——装饰器代替了 makeObservable 的第二个参数。