【问题标题】:Conditionally send JSON key in fetch有条件地在 fetch 中发送 JSON 密钥
【发布时间】:2016-11-03 06:26:40
【问题描述】:

我想“有条件地”发送一个键值。

基本上,它目前的方式仍然发送字段KEY_TEST,无论它是否包含值。

如果没有价值,我想根本不发送该字段。所以它会发送{"text":"blah","KEY_TEST":""}{"text":"blah","KEY_TEST":1}

换句话说……

如果this.props.photo.info[0] 中有值,则 fetch 应该发送:

{"text":"blah","KEY_TEST":1}

如果this.props.photo.info[0]没有值,则 fetch 应该发送:

{"text":"blah"}

这是我的完整代码:

editorUpdate: function(e) {
    e.preventDefault();
     return fetch(URL {
     method: 'PUT',
     body: JSON.stringify({
     "info": [{
            "text": this.state.value.toString('html'),
            "KEY_TEST": this.props.photo && this.props.photo.info && this.props.photo.info[0] && this.props.photo.info[0].pk || '',
      }]
      })
      })
      .then(function(res){ return res.json(); })
      .then(function(data){ alert( JSON.stringify( data ) ) })
  },

【问题讨论】:

  • 为什么在添加到正文之前不检查?
  • 请给我一个例子。我不知道它可能存在于JSON.stringify
  • 试试下面的代码

标签: json reactjs fetch


【解决方案1】:

这样试试

editorUpdate: function(e) {
     e.preventDefault();
     var keyTest = (this.props.photo && this.props.photo.info && this.props.photo.info[0]) ? {"KEY_TEST": this.props.photo.info[0].pk} : {}; 
     return fetch(URL {
     method: 'PUT',
     body: JSON.stringify({ info : [ Object.assign({
            "text": this.state.value.toString('html')
      },keyTest)]})
      })
      .then(function(res){ return res.json(); })
      .then(function(data){ alert( JSON.stringify( data ) ) })
  },

【讨论】:

  • 看起来它会起作用 - 只需稍作调整。我正在更新 OP。我的 JSON 字段实际上是嵌套的。我无法调整它
  • 你有什么问题?
  • 数据“text”嵌套在字符串“info”中。见原帖。比如这个"info": [{"text": 1,"KEY_TEST": 1,}]。我尝试了您的示例,但是当我尝试将 json 嵌套在 INFO 中时,toString('html') 后出现错误
  • 我正在尝试使用 Lodash 更有效地编写第 3 行 - 你能帮忙吗?这不是返回 pk var pk = get(this.props, 'photo.info[0].pk', '');
  • 我不熟悉lodash,但我会尽力帮助你。试试这样var pk = _.get(this.props, 'photo.info[0].pk', "");
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 2020-12-14
  • 2015-09-23
  • 2020-03-11
  • 2014-08-19
  • 2021-03-22
相关资源
最近更新 更多