【问题标题】:MobX console.log() works but render() method doesn't update using React.ComponentMobX console.log() 有效,但 render() 方法不使用 React.Component 更新
【发布时间】:2021-06-04 17:46:55
【问题描述】:

MobX 更新 console.log() 发出的存储,但实际上并没有更新 React.Componentrender() 方法。在这个例子中我遗漏了什么?

@observer
export class App extends Component {
  constructor(props) {
    super(props);
    this.onClick = this.onClick.bind(this);
  }

  @observable data = {
    error: ""
  };

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

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

CodeSandbox

来源:Stackoverflow的原始代码

【问题讨论】:

    标签: reactjs typescript state mobx-react react-state


    【解决方案1】:

    在 MobX v6 中,需要在 constructor 方法中调用 makeObservable(this) 才能使类装饰器工作。

    请参阅these docs 了解更多信息。

    有关工作示例,请参阅 this sandbox

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多