【问题标题】:Replace character in array and return result to the same array替换数组中的字符并将结果返回到同一个数组
【发布时间】:2017-02-12 18:10:51
【问题描述】:

我从 REST 服务中提取了一些数据。数据保存在this.props.message。在this.props.message 我需要替换所有“。”在offerRateprevRaterate 中使用“,”,然后将数据保存回this.props.messagethis.props.message 稍后将在表中输出(react-bootstrap-table)。可以在表格中编辑数据,在将其推回 REST 服务之前,我需要将“,”替换为“。”。

this.props.message 看起来像这样。

[Object, Object, Object, Object, Object, Object]
0:Object
    addedDate:"2013-08-22"
    ccyCode:"CHF"
    country:"SCHWIZER FRANC"
    lastChangeDate:"2016-05-02"
    offerRate:7.02
    prevRate:8.501
    prevRateDate:"2016-04-01"
    rate:8.425
    rateDate:"2016-05-01"
    unit:1
    __proto__:Object
1:Object
2:Object
3:Object
4:Object
5:Object

this.props.message 然后在表格中输出

render() {
    return (
    <div>
      <BootstrapTable 
        data={this.props.message}
        cellEdit={{
            mode: "click",
            blurToSave: true,
            afterSaveCell: this.onAfterSaveCell
        }}
      >
        <TableHeaderColumn dataField="rate" dataSort={true}>Kurs</TableHeaderColumn>
      </BootstrapTable>
    </div>

对于表中编辑的数据,我有一个名为onAfterSaveCell 的回调函数。这可能是将“,”替换为“。”的好地方。在将数据推送回 REST 服务之前。

onAfterSaveCell(row, cellName, cellValue) {
    this.props.updateData(row);
}

row 看起来像这样

Object {ccyCode: "CHF", country: "SCHWIZER FRANC", unit: 1, rateDate: "2016-05-01", rate: 8.425…}
addedDate:"2013-08-22"
ccyCode:"CHF"
country:"SCHWIZER FRANC"
lastChangeDate:"2016-05-02"
offerRate:"7.99"
prevRate:8.501
prevRateDate:"2016-04-01"
rate:8.425
rateDate:"2016-05-01"
unit:1
__proto__:Object

我还没有设法在 React 中找到替换功能。我可以采取其他方法吗?

【问题讨论】:

  • 为什么你从你的地图返回一个console.log(),而不是return message.rate.replace(',','.'),尽管它看起来像是一个数字数组?
  • "数组看起来像这样" 这不是数组,这是map 调用的代码。 数组是什么样的?
  • 我们可以看看你的 updateRow 函数吗?
  • 如果你想修改原始数组 ... map() 返回一个新数组,它不是工作的正确工具
  • @charlietfl 我应该改用什么?

标签: javascript reactjs ecmascript-6 react-jsx react-redux


【解决方案1】:

有几件事让我偏离了轨道。 this.props.messagearrayobjects。所以首先我需要遍历array 以获取object,然后遍历object 以获取我想要更改的字符。 object 中的值不是strings,所以我需要将它们转换为strings 才能使用replace 这就是我最终要做的。

replaceChar(from, to) {
    for (var i in this.props.message)
    {
      for (var p in this.props.message[i]) {
        if(this.props.message[i].hasOwnProperty(p)){
          if(p == 'rate' || p == 'prevRate' || p == 'offerRate') {
            this.props.message[i][p] = JSON.stringify(this.props.message[i][p]).replace(from,to);
          }
        }
      }
    }
  }

我从render 方法调用上面的方法,然后再渲染到表格。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 2017-10-09
    相关资源
    最近更新 更多