【问题标题】:react, mobx observale map - computed in component render not firing反应,mobx 可观察地图 - 在组件渲染中计算未触发
【发布时间】:2019-07-14 01:44:38
【问题描述】:

我有一个带有@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);

我做错了什么?

【问题讨论】:

  • 你能分享你的render()Postopki,其中PostopekView 被称为?父母render()是否被唤起?
  • @FortyTwo 用代码编辑问题。父级的渲染函数没有被调用:)

标签: reactjs mobx mobx-react


【解决方案1】:

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

我在@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,
    };
  }

一切都按预期更新。

不知道为什么……

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2017-08-24
    • 2019-03-19
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    相关资源
    最近更新 更多