首页 > 解决方案 > 有没有办法使用模板文字来获取请求?

问题描述

我想定义一个根据其参数发出提取请求的函数,这样我就可以简化 componentDidMount() 中的提取调用。我已经尝试了下面的代码,但它为 setState 函数提供了 Unexpected token 错误。有没有办法在 then() 中使用函数的参数?

 constructor() {
    super();
    // cases in date order from 1 to 5. Cases5 is the latest.
    this.state = {
      cases1: [],
      cases2: [],
      cases3: [],
      cases4: [],
      cases5: [],
    };
  }

componentDidMount() {
    fetch("/cases/1")
      .then((res) => res.json())
      .then((cases1) => this.setState({ cases1 }));

    fetch("/cases/2")
      .then((res) => res.json())
      .then((cases2) => this.setState({ cases2 }));

    fetch("/cases/3")
      .then((res) => res.json())
      .then((cases3) => this.setState({ cases3 }));

    fetch("/cases/4")
      .then((res) => res.json())
      .then((cases4) => this.setState({ cases4 }));

    fetch("/cases/5")
      .then((res) => res.json())
      .then((cases5) => this.setState({ cases5 }));
  }

  fetchCaseData = (index) => {
    fetch(`/cases${index}`)
      .then((res) => res.json())
      .then((`cases${index}`) => this.setState({ `cases${index}` }));
  }


标签: reactjsfetch

解决方案


您不能简单地为变量声明一个动态名称。但是,您可以使用方括号表示法而不是对象速记语法为对象设置动态键

更新后的代码如下所示

 .then((val) => this.setState({ [`cases${index}`]: val }));

推荐阅读