【问题标题】:React - Converting object to string to display in DevExpress React GridReact - 将对象转换为字符串以在 DevExpress React Grid 中显示
【发布时间】:2020-01-05 22:25:03
【问题描述】:

我刚刚开始使用 React 和 DevExpress React Grid。

但是我遇到了一个问题,当我尝试显示网格时出现错误: Objects are not valid as a React child.

现在看来,我需要将数据中的任何对象实例转换为字符串,即:.toString()

但是,在 DevExpress 的 React Grid 中有内置的方法来执行此操作,还是我需要手动编写一些代码来运行我的数据并更新它。

仅供参考 - 我正在使用的数据(显示在我的表格中)如下所示:

chapters: [{
        id: "chapterId1",
        code: "chapterCode",
        policies: {
            startTime: "2016-08-29T09:12:33.001Z",
            endTime: "2016-08-29T09:12:33.001Z",
        },
}]

谢谢。

【问题讨论】:

  • 哪里出错了?
  • 当您尝试直接渲染对象时会发生该错误。您需要先将对象呈现为字符串(通过.toString()JSON.stringify(chapters))以这种方式显示它
  • 嘿,我正在尝试 JSON.stringify 但运气不佳。所以 chapters 本身已经是一个数组。因此,当我将它传递给rows 时,例如:rows={props.chapters},我觉得它希望我传递给rows={[props.chapters.toString()]},但随后我将包装到另一个数组中?同样作为字符串,DevExpress 网格是否可以实际获取键、值?

标签: javascript reactjs typescript devexpress


【解决方案1】:

问题可能是policies 键。看起来这个库正在尝试直接呈现该值,但该值是一个对象。

一种选择是手动将此值“展平”为单个值或两个单独的值。例如:

{
  id: "chapterId1",
  code: "chapterCode",
  policies: "2016-08-29T09:12:33.001Z - 2016-08-29T09:12:33.001Z"
}

如果你想区分列,另一种方法:

{
  id: "chapterId1",
  code: "chapterCode",
  policiesStart: "2016-08-29T09:12:33.001Z",
  policiesEnd: "2016-08-29T09:12:33.001Z"
}

我没有完整的上下文,但假设您想格式化这些日期,您可以创建一个帮助程序(例如:transformRows),它接受您当前的输入并构造这个新输入(并执行日期格式化等额外工作) :

const chapters = [
  {
    id: "chapterId1",
    code: "chapterCode",
    policies: {
      startTime: "2016-08-29T09:12:33.001Z",
      endTime: "2016-08-29T09:12:33.001Z"
    }
  }
];

const transformRows = rows =>
  rows.map(({ policies, ...rest }) => ({
    policiesStart: policies.startTime,
    policiesEnd: policies.endTime,
    ...rest
  }));

const App = () => (
  <Grid
    rows={transformRows(chapters)}
    columns={[
      { name: "id", title: "ID" },
      { name: "code", title: "Code" },
      { name: "policiesStart", title: "Policies" },
      { name: "policiesEnd", title: "Policies" }
    ]}
  >
    <Table />
    <TableHeaderRow />
  </Grid>
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-14
    • 2021-01-19
    • 2017-09-13
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 2021-01-28
    相关资源
    最近更新 更多