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

React.js中如何调用函数数组内匹配指定类型的对应函数

代码错误点

你的逻辑错误出在函数取值这一行:var func = functions.indexOf(options.indexOf(this.state.type));

  • options.indexOf(this.state.type)会返回当前type在options数组里的数字索引,匹配到BTC返回0、ETH返回1、ADA返回2,找不到就返回-1
  • 你接着对存了3个函数的functions数组调用indexOf(数字),相当于在函数列表里找和数字相等的元素,永远匹配不到,返回值固定是-1,根本拿不到目标函数,执行自然报错。
修正方法

最小改动版(沿用你数组的思路)

拿到索引后直接按数组下标取对应函数,不要用indexOf在函数数组里找数字,加个边界判断避免非法type报错:

componentDidMount() {
  const options = ["BTC", "ETH", "ADA"];
  const functions = [this.getBTC, this.getETH, this.getADA];
  const typeIndex = options.indexOf(this.state.type);
  if (typeIndex === -1) return;
  const func = functions[typeIndex];
  func();
}

注:你定义的getBTC/getETH/getADA都是箭头函数类属性,已经自动绑定了组件this,不需要额外写.call(),直接调用即可。

推荐写法(对象映射,更好维护)

不用维护两个顺序必须严格对应的数组,直接建类型到函数的映射表,代码可读性更高,后续加新类型也不容易出错:

componentDidMount() {
  const funcMap = {
    BTC: this.getBTC,
    ETH: this.getETH,
    ADA: this.getADA
  };
  const targetFunc = funcMap[this.state.type];
  if (typeof targetFunc === "function") {
    targetFunc();
  }
}
额外优化提示

你现在在constructor里把props.data赋值给state.type的写法,后续如果父组件更新传入的data值,state里的type不会自动同步。如果需要跟随prop变化重新执行对应获取数据的函数,需要补充componentDidUpdate生命周期做判断:

componentDidUpdate(prevProps) {
  // 当传入的data变化时,重新执行对应函数
  if (prevProps.data !== this.props.data) {
    this.setState({
      type: this.props.data
    }, () => {
      // state更新完成后调用对应函数,逻辑和componentDidMount里的一致即可
      const funcMap = {
        BTC: this.getBTC,
        ETH: this.getETH,
        ADA: this.getADA
      };
      const targetFunc = funcMap[this.state.type];
      if (typeof targetFunc === "function") targetFunc();
    })
  }
}

内容的提问来源于stack exchange,提问作者roee attias

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 16:36:26