You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中重载React类组件的place getter

重载React类组件的place getter以替换menu数据源

要实现访问this.place.menu时从非Mobx资源获取数据,你可以通过代理(Proxy)或对象属性重写的方式包装Mobx返回的place对象,仅替换menu属性的数据源,同时保留其他属性的原有逻辑。

方法一:使用Proxy(推荐,保留Mobx响应式)

Proxy可以拦截对象的属性访问,仅在访问menu时返回非Mobx数据,其他属性依然沿用Mobx模型的响应式数据:

get place() {
  return new Proxy(this.mobx.place, {
    get(target, prop) {
      if (prop === 'menu') {
        // 替换为你的非Mobx数据源获取逻辑
        return this.getMenuFromOtherSource();
      }
      // 其他属性返回Mobx模型的原数据
      return target[prop];
    }
  }.bind(this)); // 绑定组件this,确保能调用内部方法
}

// 自定义非Mobx数据源获取方法
getMenuFromOtherSource() {
  // 示例:从本地存储、API缓存或其他非Mobx状态取数据
  const menuCache = localStorage.getItem('customMenu');
  return menuCache ? JSON.parse(menuCache) : { items: [] };
}

方法二:对象扩展+重写属性(简单但丢失响应式)

如果不需要保留其他属性的Mobx响应式,可以直接扩展原place对象,重写menu的getter:

get place() {
  const mobxPlace = this.mobx.place;
  return {
    ...mobxPlace,
    // 重写menu属性,指向非Mobx数据源
    get menu() {
      return this.getMenuFromOtherSource();
    }
  };
}

getMenuFromOtherSource() {
  // 你的非Mobx数据获取逻辑
}

注意事项

  • 若Mobx的place是可观察对象,Proxy方式能完整保留其他属性的响应式,适合需要实时更新的场景;
  • 对象扩展方式会将原可观察对象转为普通对象,其他属性失去Mobx响应式,仅适合静态数据场景;
  • 如果非Mobx数据是异步获取,需要结合组件状态处理加载状态,比如先返回默认菜单,等数据加载完成后更新组件。

完整组件示例

import React from 'react';
import { observer } from 'mobx-react';

@observer
class PlaceComponent extends React.Component {
  get place() {
    return new Proxy(this.mobx.place, {
      get(target, prop) {
        if (prop === 'menu') {
          return this.getMenuFromOtherSource();
        }
        return target[prop];
      }
    }.bind(this));
  }

  getMenuFromOtherSource() {
    const menuData = localStorage.getItem('userCustomMenu');
    return menuData ? JSON.parse(menuData) : { items: [] };
  }

  componentDidMount() {
    console.log(this.place.menu); // 输出非Mobx数据源的菜单
    console.log(this.place.name); // 输出Mobx模型的原属性
  }

  render() {
    const { place } = this;
    return (
      <div>
        <h2>{place.name}</h2>
        <ul>
          {place.menu.items.map(item => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      </div>
    );
  }
}

export default PlaceComponent;

内容的提问来源于stack exchange,提问作者What is Love

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 09:52:35