首页 > 解决方案 > 将属性添加到 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
            })
        };
    }
 }

标签: javascriptreactjs

解决方案


使用 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
}

推荐阅读