json - 每个选择选项的反应 API 调用
问题描述
我有这个接收选择选项值的功能。此外,我有 3 个选择选项(级别、设施、主机)。当我选择选项时,值将发送到此函数。
private optionFilterHandler = (option: string, key: string | number) => {
// the key can be level , facility , host
// whereas options are the values of keys
// for level option values are (debug , warning ,info etc)
// similarly for host and facility have options values
if (option || key) {
this.setState({
option: option,
key: key,
},
this.filterHandler
); // callback function
}
然后作为选项和键存储在状态中
问题是我需要将所有三个选项都发送到 API,例如:API 调用应该是这样的
private filterHandler = async () => {
const response: Response = await fetch(
'http://egrde-tvm-aso1.de.egr.lan:3000/api/v1/search',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
facility: this.state.option,
level: this.state.option,
host: this.state.option
});
});
}
那么我应该如何在 json.Stringify({}) 中发送所有三个选项,因为每次选择选项时我只得到一个选项值以及如何检查选项值是否属于级别、设施或主机。
解决方案
您可以更改您的状态以拥有一个收集所有选项的对象。然后在事件处理程序中,您可以将选项分配给属性key
。此外,也许您打算在事件处理程序中使用&&
而不是?||
constructor(props) {
super(props);
this.state = {
options: {
level: undefined,
facility: undefined,
host: undefined
}
};
}
private optionFilterHandler = (option: string, key: string | number) => {
if (option && key) {
this.setState(
{
options: { ...this.state.options, [key]: option }
// copies the old options object and sets the property `key` to
// the value `option`
// Uses "computed property names": https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names
},
this.filterHandler
);
}
};
private filterHandler: Response = async () => {
const { level, facility, host } = this.state.options
// ⮤ object destructuring: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring
if (!level || !facility || !host) {
// Don't fetch unless all options are present (remove this if
// it's okay to fetch with partial options)
return
}
const response = await fetch(
'http://egrde-tvm-aso1.de.egr.lan:3000/api/v1/search',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state.options)
}
);
};
推荐阅读
- javascript - 以短时间间隔多次触发弹出窗口
- html - HTML:页脚宽度问题
- python - 条件滚动平均值
- unity3d - Unity GridLayoutGroup 动态创建单元格大小问题
- c - C宏赋值
- javascript - 忽略 Google 表格自定义脚本中的空单元格
- flutter - VS Code 自动完成重新导入具有完整路径的包
- r-markdown - RMarkdown 找不到“pdflatex.fmt”文件
- python - Django/Pandas - 当我尝试将文件保存到表单时,上传的文件在 / 处获取“MultiValueDictKeyError”,然后是整个数据库
- svelte - 如何在 Svelte 中创建打印按钮?