组件对嵌套的Mobx存储没有反应

时间:2019-04-09 15:49:02

标签: mobx mobx-react

我正在基于MobX中的嵌套商店(SquareModel)渲染正方形。单击正方形后,我希望在SquareModel内触发一个操作,更改一个selected属性,该属性将依次调整正方形的大小。但是,我似乎无法使平方对属性更改做出反应。关于如何使它正常工作的任何想法?

沙箱:https://codesandbox.io/s/m51oyzz069

MainStore:

import { observable, decorate } from "mobx";
import SquareModel from "./SquareModel";

class MobXStore {
  square = new SquareModel();
}

decorate(MobXStore, {
  square: observable
});

export default new MobXStore();

NestedStore:

import { observable, action, decorate } from "mobx";

class SquareModel {
  selected = false;
  toggleSelection() {
    console.log("toggle selection");
    this.selected = !this.selected;
  }
}

decorate(SquareModel, {
  selected: observable,
  toggleSelection: action
});

export default SquareModel;

反应:

const App = observer(() => {
  return (
    <svg className="App">
      <svg x={100} y={100}>
        <Square
          unit={MobXStore.square.selected ? 2 : 1}
          onPointerUp={MobXStore.square.toggleSelection}
        />
      </svg>
    </svg>
  );
});

export const Square = observer(({ unit, ...props }) => {
  console.log("render square");
  return (
    <g {...props}>
      <rect height={unit * 50} width={unit * 50} style={{ fill: "blue" }} />
    </g>
  );
});

1 个答案:

答案 0 :(得分:1)

toggleSelection方法中的“ this”存在错误

它应该像这样:

Expected output
----------------------
date            A    B
2019-01-01      1    a      (take from df)
2019-01-02      2    b      (take from df_new)
2019-01-03      3.5  c1     (take from df_new)
2019-01-04      4    d      (take from df_new)
2019-01-05      5    e      (take from df_new)
2019-01-06      6    f      (take from df_new)

或者您需要在此处使用例如箭头功能:

onPointerUp = {() => MobXStore.square.toggleSelection()}