设置has方法不会为现有对象返回true

时间:2018-07-09 21:57:33

标签: javascript reactjs typescript set stackblitz

这是我的闪电战:

https://stackblitz.com/edit/svgtest

JSX

import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
import { observer } from 'mobx-react';
import { observable } from 'mobx';
import { MountingViewModel } from './MountingViewModel';
import { Roof } from './roof';
import { Facade } from './facade';

interface AppProps { }
interface AppState {
  name: string;
}

@observer
class App extends Component<AppProps, AppState> {
  constructor(props) {
    super(props);
    this.state = {
      name: 'React'
    };
  }

  onClick = (e) => {
    alert(e.currentTarget.id);
    // set opcacity to 0.5 to all others id`s
  }

  @observable mountings: Set<MountingViewModel> = new Set();

  roofViewModel: MountingViewModel = new MountingViewModel(false, "roof");
  facadeViewModel: MountingViewModel = new MountingViewModel(false, "facade");

  componentDidMount() {
    this.mountings.add(this.roofViewModel);
    this.mountings.add(this.facadeViewModel);
  }

  renderSvg() {
    return <svg height="400" width="400" xmlns="http://www.w3.org/2000/svg">
      {  
        this.mountings.has(this.roofViewModel) && <Roof id={"roof"} />
      }
      {
        this.mountings.has(this.facadeViewModel) && <Facade id={"facade"} />
      }

    </svg>
  }

  onMouseOver = (e) => {
    let data = e.currentTarget;
    alert(data.style);
  }

  render() {
    return this.renderSvg()

  }
}

render(<App />, document.getElementById('root'));

由于Set.has方法没有返回true,所以屋顶和外墙组件未呈现,尽管我会说对象相等!

为什么没有渲染这两个组件?

1 个答案:

答案 0 :(得分:0)

MobX doesn't support observable Sets yet。相反,您可以将视图保留在一个可观察的数组中,并且当数组更改时,组件将按原样重新渲染。

@observer
class App extends Component<AppProps, AppState> {
  // ...

  @observable mountings: MountingViewModel[] = [];

  componentDidMount() {
    this.mountings.push(this.roofViewModel);
    this.mountings.push(this.facadeViewModel);
  }

  renderSvg() {
    return <svg height="400"   width="400" xmlns="http://www.w3.org/2000/svg">
      {  
        this.mountings.indexOf(this.roofViewModel) === -1 && <Roof id={"roof"} isSelected={this.roofViewModel.isSelected}  />
      }
      {
        this.mountings.indexOf(this.facadeViewModel) === -1 && <Facade id={"facade"} isSelected={this.facadeViewModel.isSelected} />
      }
    </svg>
  }

  render() {
    return this.renderSvg()
  }
}