reactjs - 有没有办法使用模板文字来获取请求?
问题描述
我想定义一个根据其参数发出提取请求的函数,这样我就可以简化 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}` }));
}
解决方案
您不能简单地为变量声明一个动态名称。但是,您可以使用方括号表示法而不是对象速记语法为对象设置动态键
更新后的代码如下所示
.then((val) => this.setState({ [`cases${index}`]: val }));
推荐阅读
- azure-log-analytics - 巧妙地格式化毫秒
- python - 熊猫替换一列中的值基于另一列
- python - 无法让 Flask、Gunicorn 和 Nginx 工作
- vba - 将excel表格分解为文本文件 - 格式化
- excel - 如何留出时间通过 Excel 中的 VBA 从 Bloomberg 刷新 BDH 公式?
- javascript - 如何将 UL 元素插入列表
- ejs - 如何从Nodejs的上传文件夹上传Ejs中的img
- sql - SQL 查询以获取最新创建的具有属性的所有行
- firebase - 是否应该对所有发布请求进行 CSRF 检查?
- python - 1064, "您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,以获取在 '%s 附近使用的正确语法)