在MobX里面,对于一个带有prototype的object,MobX并不会默认把它设置为observable。因为MobX认为这是这个对象的构造函数需要去管理的事情。这里,我们有2种方式:
1:在constructor里面使用extendObservable

import {extendObservable, observable} from 'mobx'
import {observer} from 'mobx-react'
import {Component} from 'react'
import React from 'react'
import ReactDom from 'react-dom'
class Rectangle{
  id = Math.random();
  constructor(width, height){
    extendObservable(this, {
      width: width,
      height: height
    })
  }
  increaseWidth = ()=>{
    this.width ++;
  }
}

 @observer class RectangleInfo extends Component {
  render(){
    return (
      <div>
        {
          this.props.rectangles.map((item, index)=>
          <div key={item.id}>
            <div>width: {item.width}</div>
            <button onClick = {item.increaseWidth}> + </button>
          </div>
          )
        }
      </div>
    )
  }
}

let rectangles = observable([new Rectangle(0, 0), new Rectangle(10, 10)]);
const rootElement = document.getElementById('root');
ReactDom.render(<RectangleInfo rectangles = {rectangles}/>, rootElement);

2:在class定义的时候,使用@observable/decorate

import {extendObservable, observable} from 'mobx'
import {observer} from 'mobx-react'
import {Component} from 'react'
import React from 'react'
import ReactDom from 'react-dom'
class Rectangle{
  id = Math.random();
  //没有使用extendObservable,但是使用@observable
  @observable width;
  @observable height;
  constructor(width, height){
    this.width = width;
    this.height = height
  }
  increaseWidth = ()=>{
    this.width ++;
  }
}

 @observer class RectangleInfo extends Component {
  render(){
    return (
      <div>
        {
          this.props.rectangles.map((item, index)=>
                <div key={item.id}>
                    <div>width: {item.width}</div>
                    <button onClick = {item.increaseWidth}> + </button>
                </div>
          )
        }
      </div>
    )
  }
}

let rectangles = observable([new Rectangle(0, 0), new Rectangle(10, 10)]);
const rootElement = document.getElementById('root');
ReactDom.render(<RectangleInfo rectangles = {rectangles}/>, rootElement);

以上就是2种处理带prototype的对象(也就是在class),使得对象成为observable的方法。


nanaistaken
586 声望43 粉丝