【问题标题】:React Transforming Server Response (adding extra field to an Object)React 转换服务器响应(向对象添加额外字段)
【发布时间】:2019-01-17 02:23:26
【问题描述】:

我有一个发送 axios GET 请求并将响应(对象数组)设置为状态的基本函数。

getData(){
  axios.get(url)
    .then(response => this.setState({ data: response.data })
}

但是我想向对象添加一个附加字段。我该怎么做?

我认为是这样的:

getData(){
  axios.get(url)
    .then(response => transformRes(response.data))
    .then(newResponse => this.setState({ data: newResponse })
}

transformRes(data){
  data.forEach(d => {
    // do something ??
  }
  // return newData ??
}

模拟示例数据(来自服务器)

(2) [{...}, {...}]

0: {id: 1, name: 'foo'}
1: {id: 2, name: 'bar'}

模拟预期结果(transformRes 之后)

(2) [{...}, {...}]

0: {id: 1, name: 'foo', desc: 'active'} // added desc field.
1: {id: 1, name: 'bar', desc: 'active'} // added desc field. 

【问题讨论】:

    标签: javascript arrays reactjs object axios


    【解决方案1】:

    只需在地图函数中添加属性:

    getData(){
      axios.get(url)
        .then(response => {
           const res = response.data
           this.setState({ data: res.map(object => {
             return {...object, desc: 'active'}
            })})
        })
    }
    

    顺便说一句,... 是扩展运算符,...object 表示object 中的每个key/value

    【讨论】:

    • 如果您没有可用的扩展运算符,您可以使用 Object.assign 代替它(如果您正在使用反应,您可能会这样做)。
    • 谢谢,这行得通。解释也很好。不过我不得不做些小改动。
    【解决方案2】:

    基本上,您希望将旧对象映射到新对象。使用.forEach,您在正确的轨道上

    getData() {
        axios.get(url)
            .then(response => {
                var newData = response.map((data) => {
                    data.desc = 'active'; //add your properties here
                    return data;
                });
                this.setState({data: newData});
            });
    }
    

    如果这不适用于您的情况或您有疑问,请告诉我。

    【讨论】:

    • 我必须复制每个字段吗?例如data.id = data.id ?
    • 其实我把上面的代码搞砸了。请查看固定版本。不,您不必复制现有字段,只需复制新字段即可。
    猜你喜欢
    • 2015-10-09
    • 2017-04-17
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 2019-12-30
    • 2018-01-19
    相关资源
    最近更新 更多