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

时间:2019-02-20 11:22:26

标签: reactjs mobx mobx-react

我有一家带有@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的render函数不会触发,即使计算出的返回值不同。

编辑-这是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);

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

找到了计算结果未触发的原因...

我有在@computed中调用的方法:

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

直接在方法中引用可观察对象后:

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

一切都会按预期进行。

不知道为什么...