【发布时间】:2021-08-25 19:57:42
【问题描述】:
我有一个 React 表 (react-table),它从 api 接收数据以填充行单元格。数据看起来像这样:
const data = [{id: "6666", contact_id: "1", poc_id: "2", contact: "John Doe",
watersheds: "{12070104,12090301,12090401}"}, {id: "6667", contact_id: "2",
poc_id: "3", contact: "Sally Jones", watersheds: "{12070105,12090301}"}]
根据API 请求返回的内容,可能会有更多或更少的项目。我的问题是当Watershed 列填充watershed 数据项时,它包括{ ... }s。我希望它在单元格中返回12070104,12090301,12090401,而不是{12070104,12090301,12090401}。我知道我可以使用replace 或其他方法来删除和替换不需要的{ }s:
data.map(item => (item.watersheds.replace(/{/gi, "").replace(/}/gi, "")))
或类似的东西,但由于我将数据动态添加到表中,我不确定如何在 { }s 显示在表中之前删除它们?我的桌子看起来像这样:
import React from 'react'
import styled from 'styled-components'
import { useTable } from 'react-table'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
table {
border-spacing: 0;
border: 1px solid black;
tr {
:last-child {
td {
border-bottom: 0;
}
}
}
th,
td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid black;
border-right: 1px solid black;
:last-child {
border-right: 0;
}
}
}
`
function Table({ columns, data }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable({
columns,
data,
})
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map((row, i) => {
prepareRow(row)
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
})}
</tr>
)
})}
</tbody>
</table>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'ID',
accessor: 'id',
},
{
Header: 'CONTACT ID',
accessor: 'contact_id',
},
{
Header: 'POC ID',
accessor: 'age',
},
{
Header: 'NAME',
accessor: 'contact',
},
{
Header: 'Watersheds',
accessor: 'watersheds',
}
], []
)
//const data = React.useMemo(() => makeData(20), [])
const data = useMemo(() => [{id: "6666", contact_id: "1", poc_id: "2", contact: "John Doe",
watersheds: "{12070104,12090301,12090401}"}, {id: "6667", contact_id: "2",
poc_id: "3", contact: "Sally Jones", watersheds: "{12070105,12090301}"}])
return (
<Styles>
<Table columns={columns} data={data} />
</Styles>
)
}
export default App
【问题讨论】:
标签: reactjs replace cell react-table