@computed方法在React + Mobx中不起作用

时间:2018-09-24 19:44:28

标签: reactjs mobx mobx-react

我是React和Mobx的新手。我试图仅使用@computed方法作为示例。我有复选框,更改后,状态(用户名)更改,但是@computed方法不会调用。这是我的代码:

LoginStore.js:

import { computed, observable } from "mobx";

class LoginStore {

  @observable
  username = "Daimon";

  @computed
  get report() {
    return this.username + "12345";
  }

}

var store = new LoginStore;
export default store;

自动化:

import React, { Component } from 'react';
import { observer } from "mobx-react";

@observer
class Autorization extends Component {
  test = () => {
    this.props.store.username = "krikkk";
  }
  render() {
    return (
      <body>
        <p>{this.props.store.username}</p>
        <input type="checkbox" class="custom-control-input" id="customCheck1" onChange={this.test}/>
      </body>
    );
  }
}

export default Autorization;

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import Autorization from './Autorization';
import registerServiceWorker from './registerServiceWorker';
import loginStore from "./stores/LoginStore";

ReactDOM.render(<Autorization store={loginStore}/>, document.getElementById('root'));
registerServiceWorker();

package.json:

{
  "name": "autorization",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "custom-react-scripts": "^0.2.2",
    "mobx": "^5.1.2",
    "mobx-react": "^5.2.8",
    "react": "^16.5.2",
    "react-dom": "^16.5.2",
    "react-scripts": "1.1.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-decorators-legacy": "^1.3.5"
  }
}

有人知道如何解决吗?

1 个答案:

答案 0 :(得分:1)

更改用户名后,不会重新调用您的@computed方法,因为报告方法本身未在任何有效位置使用。

来自官方mobx文档:

  

任何影响计算值的值都会自动从状态中得出。 MobX在许多情况下都可以优化计算值,因为它们被认为是纯净的。例如,如果先前计算中使用的数据均未更改,则计算的属性将不会重新运行。 如果其他某些计​​算属性或反应未使用该计算属性,也不会重新运行。在这种情况下,它将被暂停。

要进行测试,可以在“授权”组件的呈现上进行更改

        <p>{this.props.store.username}</p>

        <p>{this.props.store.report}</p>