本文介绍了如何在React.js中替换数组值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在React.js中的示例代码.我想使用Main.jsConstants.js中的数组distances.特别是,应使用来自Constants.js的数组distances中的相应value替换sampleData中的APT列.

This is my sample code in React.js. I want to use an array distances from Constants.js in Main.js. In particular, the column APT in sampleData should be substituted by an appropriate value from an array distances taken from Constants.js.

因此,在单击按钮Load data之后,对象csvData最终应如下所示:

Thus, after clicking on the button Load data, the object csvData should finally look as follows:

NUM,APT,COST
1,483,20
2,5777,25
3,5777,15

Constants.js

export const distances = [
  {label:"KJFK",value:5777},
  {label:"ERTE",value:483}
]

Main.js

import React, { Component } from 'react';
import { CsvToHtmlTable } from 'react-csv-to-table';
import ReactFileReader from 'react-file-reader';
import Button from '@material-ui/core/Button';
import {distances} from './Constants';

const sampleData = `
NUM,APT,COST
1,ERTE,20
2,KJFK,25
3,KJFK,15
`;

class CSVDataTable extends Component {

    state={
      csvData: sampleData
    };

    handleFiles = files => {
        var reader = new FileReader();
        reader.onload =  (e) => {
          // Use reader.result
          this.setState({
            csvData: reader.result
          })
          this.props.setCsvData(reader.result)
        }
        reader.readAsText(files[0]);
    }

    render() {
        return <div>
          <ReactFileReader
            multipleFiles={false}
            fileTypes={[".csv"]}
            handleFiles={this.handleFiles}>
            <Button
                variant="contained"
                color="primary"
            >
                Load data
            </Button>

          </ReactFileReader>
          <CsvToHtmlTable
            data={this.state.csvData || sampleData}
            csvDelimiter=","
            tableClassName="table table-striped table-hover"
          />
    </div>
    }
}

export default CSVDataTable;

我尝试了以下操作:

function myFunc(item, index) {
  if (item["APT"]=="ERTE") {
    return 483
  }
  else {
    return 5777
  }
}

this.setState({
   csvData: reader.result.forEach(myFunc)
})

但是此更新后,代码无法编译.

But the code does not compile after this update.

推荐答案

您可能可以在

const replacedValues = distances.reduce((acc, d) => {
    const regex = new RegExp(`${d.label}`, 'g')
    return acc.replace(regex, d.value)
}, sampleData)

这将遍历所有可能的距离",将等于distance.label的任何值替换为distance.value,并返回应用了所有更改的最终字符串.

This will iterate over all the possible "distances", replace any value equal to distance.label with distance.value and return the final string with all the changes applied.

您可以这样做

this.setState({
   csvData: replacedValues
})


添加到此答案中,您可以创建一个函数,该函数将距离给定字符串中匹配的所有值动态替换为距离常数中的值.


Adding to this answer, you could create a function that dynamically replaces all values that match in a given string with the values from your distances constants.

const replaceDistances = data =>
  distances.reduce(
    (acc, d) => acc.replace(new RegExp(`,${d.label},`, "g"), `,${d.value},`),
    data
  );

// And whenever you load values

this.setState({
   csvData: replaceDistances(reader.result) // or sampleData
})

这篇关于如何在React.js中替换数组值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 17:39