将属性添加到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
}

我认为您可以将代码简化为这样。

handleSubmit(event) {
var requestOptions = {}
const params = new URLSearchParams({
'name': this.state.name,
'birth': this.state.birth,
'oscars': this.state.oscars
});
if (this.state.movies.length > 0) {
params.append("movies", this.state.movies)
}
requestOptions.method = "POST";
requestOptions.body = params;
}

最新更新