javascript - 将属性添加到 javascript urlSearchParams 对象
问题描述
我有这段我认为可能更简单的代码,现在我正在创建一个对象并在 if 的两个条件下分配属性
handleSubmit(event) {
var requestOptions = {}
if(this.state.movies.length === 0 ){
requestOptions = {
method: 'POST',
body: new URLSearchParams({
'name': this.state.name,
'birth': this.state.birth,
'oscars': this.state.oscars
})
};
}else{
requestOptions = {
method: 'POST',
body: new URLSearchParams({
'name': this.state.name,
'birth': this.state.birth,
'oscars': this.state.oscars,
'movies': this.state.movies
})
};
}
}
解决方案
使用 Object.assign
new URLSearchParams(Object.assign({
name: this.state.name,
birth: this.state.birth,
oscars: this.state.oscars
}, this.state.movies.length && {
movies: this.state.name
}))
或先创建它并有条件地附加它
query = new URLSearchParams(Object.assign({
name: this.state.name,
birth: this.state.birth,
oscars: this.state.oscars
})
this.state.movies.length && query.append('movies', this.state.movies)
requestOptions = {
method: 'POST',
body: query
}
推荐阅读
- javascript - django-js-routes 解析器找不到 url
- c# - Dotnet 5.0 数据保护(到 Azure Vault 的持久密钥)解包密钥随机失败:“[未知] 验证令牌时出错:'S2S12086'”
- python - 如何检查列是否存在
- laravel - Laravel 8 - 我正在使用多输入文件,无法将多个图像存储在不同的行(DB)
- css - 使尺寸适合屏幕的高度
- sql - 如何进行高级 PIVOT
- flutter - 在 Flutter 中将 ieee754 半精度字节转换为双精度,反之亦然
- mysql - 当某些数据是有条件的时,如何从 Django 中的两个表中查询数据
- svg - 单击或鼠标悬停时缩放整个 SVG 组的 SVG 元素
- python - Pandas - Select values depending on a value in a DataFrame made of a deeply nested dictionary