反应,mobx可观察地图 - 在组件中计算渲染不触发

问题描述 投票:0回答:1

我有一个商店有@observable地图。使用@computed函数读取此地图中的数据。

export class Postopki {
  @observable data = new Map<string, PostopekObservableType>([]);
  @observable activeId: string;

  // gets the postopek data for the current active id
  @computed get getActive(): PostopekObservableType {
    const postopek = this.getById(this.activeId);
    if (postopek) {
      return toJS(postopek);
    }
    return {
      canView: false,
      canEdit: false,
    };
  }
  ...

然后我有另一个@action在可观察地图中的对象上设置属性:

@action setCenilecId = (idCenilec: string): void => {
    const postopek = this.getActive;
    postopek.idCenilec = idCenilec;
    // updates postopek data with the new idCenilec
    this.addPostopek(this.activeId, postopek);

    console.group('setCenilecId');
    console.log('new postopek data', postopek);
    console.log('postopek observable', this.getActive);
    console.groupEnd();
  };

最后我在组件的渲染中使用我的计算器:

@inject('postopki')
@observer
class PostopekView extends Component<any, State> {
  render() {
    const postopek = this.props.postopki.getActive;
    console.log('Postopek view:', postopek);

    return (
      <StyledDiv>
        ...
      </StyledDiv>
    );
  }
}

当调用setCenilecId时,我使用getActive计算机将更新的数据记录到控制台。

但是,即使计算的返回值不同,PostopekView的渲染函数也不会触发。

编辑 - 这是postopekView组件的父组件。

@inject('postopki')
@observer
class Postopek extends Component<any, State> {
  state: State = {
    isLoading: true,
    hasError: false,
    errorMessage: '',
  };

  // gets initial postopek data based on the id from props when component first mounts
  componentDidMount = async (): Promise<void> => {
    ...
  };

  // updates postopek data when a new id is passed from router
  componentDidUpdate = async (prevProps: any): Promise<void> => {
   ...
  };

  render() {
    const { isLoading, hasError, errorMessage } = this.state;

    return (
      <WithStatus isLoading={isLoading} hasError={hasError} errorMessage={errorMessage}>
        <PostopekView />
      </WithStatus>
    );
  }
}

export default withRouter(Postopek);

我究竟做错了什么?

reactjs mobx mobx-react
1个回答
0
投票

找到计算机没有触发的原因......

我有这个方法,我在@computed调用:

  @action getById = (id: string): PostopekObservableType | undefined => {
    const postopek = (this as any).data.get(id);
    return postopek;
  };

在我直接引用方法中的observable之后:

@computed get getActive(): PostopekObservableType {
    const postopek = this.data.get(this.activeId);
    if (postopek) {
      return toJS(postopek);
    }
    return {
      canView: false,
      canEdit: false,
    };
  }

一切都按预期更新。

不知道为什么......

© www.soinside.com 2019 - 2024. All rights reserved.