简单的 MobX Observable 不渲染 [英] Simple MobX Observable not Rendering

查看:160
本文介绍了简单的 MobX Observable 不渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 React 类,用 MobX @observer 注释和简单的数据结构(用 @observable data = { .. } 注释.一个动作更新这个结构,但确实呈现.

这里是类的源代码:-

import React, {Component, Fragment} from 'react';从mobx-react"导入{观察者};从mobx"导入 {observable};从'react-router-dom'导入{withRouter};@观察者@withRouter类 UpdateDetailsForm 扩展组件 {构造函数(道具){超级(道具);this.onClick = this.onClick.bind(this);}@observable 数据 = {错误: ""};点击(){this.data.error = "发生错误";console.log("出事了!");//测试目的}使成为() {返回 (<div><div className="red">[ {this.data.error} ]</div><input type="button" value="点击我!"onClick={this.onClick}/>

);}}

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

出事了!

... 证明 data 的状态发生了变化,但 HTML 没有更新.

解决方案

刚刚想通了!类注释的顺序很重要,即

@withRouter@观察者类 UpdateDetailsForm 扩展组件 {...

这有效!

但是当 @withRouter 是最接近 class UpdateDetailsForm 的注解时,它会失败.

也在 MobX 文档中找到了这个 - https://mobx.js.org/best/陷阱.html

<块引用>

_@inject('store')@observer 之前会导致 MobX 不触发_

所以 @inject 注释也会发生同样的事情.

I have a simple React class annotated with a MobX @observer annotation and a simple data structure (annotated with @observable data = { .. }. An action updates this structure but does render.

Here is source code of the class: -

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>      
    );
  }

}

However, when I click the button the console displays ...

Something has happened!

... which proves the state of data is mutated but the HTML doesn't update.

解决方案

Just figured it out! It was the order of the class annotations is important i.e.

@withRouter
@observer
class UpdateDetailsForm extends Component {

...

This works!

But when @withRouter is the closest annotation to class UpdateDetailsForm it fails.

Also found this in MobX docs - https://mobx.js.org/best/pitfalls.html

_@inject('store') before @observer will cause MobX to not trigger_

So the same thing happens for the @inject annotation.

这篇关于简单的 MobX Observable 不渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆