Метод set has не возвращает true для существующего объекта

Вот мой стекблиц:

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, хотя я бы сказал, что равенство объектов задано!

Почему эти 2 компонента не отображаются?

1 ответ

MobX пока не поддерживает наблюдаемые наборы. Вместо этого вы можете хранить ваши представления в наблюдаемом массиве, и ваш компонент будет перерисовываться так, как должен, когда массив изменяется.

@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()
  }
}
Другие вопросы по тегам