【问题标题】:Make the data selection from object to be dry使对象的数据选择干燥
【发布时间】:2020-07-30 19:31:09
【问题描述】:

关于我应该如何在下面处理这个问题的快速问题。我有来自后端的数据,在前面我使用反应我有一个基本上是表格的组件。两个 api 调用女巫返回不同的对象。我想重用一个组件,而不是创建两个单独的表,如下所示。我将一个数据对象传递给一个表格组件,只需要知道根据对象选择哪些键即可。

      <table>
          <tbody>
            <tr>
              <td>{name}</td>
              <td>{first_test.week_day}</td>
              <td>{first.four.three}</td>
            </tr>
          </tbody>
        </table>

       <table>
          <tbody>
            <tr>
              <td>{name}</td>
              <td>{test.time}</td>
              <td>{another.one.two}</td>
            </tr>
          </tbody>
        </table>

两个单独的 api 请求示例:

  {
     first: {four: {three: "different"}},
     first_test: {week_day: 'Saturday'},
     name: "first test"
  }
  {
    another: {one: {two: "nice"}},
    test: {time: 10:00},
    name: "test"
  }
   

那么在不创建多个组件的情况下处理这种干燥的最佳方法是什么?也许是一些 json 架构?

如果有人放弃另一个相关问题,可能会重复。

【问题讨论】:

  • 您当前的实现有什么问题?仅当存在显着的可重复差异时,您才应创建更多组件。
  • 是说 name、test 和另一个是单独的 api 请求吗?你不是用一些函数把它们组合成一行吗?
  • @SILENT 更新了这个问题,这可能使它更清楚一点,基本上我想为几个具有不同数据的 api 请求重用相同的表组件,但是如果我指定选择哪个对象键,它就不会干因为该键可能不在另一个 api 调用中。希望那更清楚:)

标签: javascript reactjs object components dry


【解决方案1】:

您遵循任何输入以匹配您的通用表格组件,就像这样

function GenericTable({first, second, third}) {
return (
<table>
  <tbody>
    <tr>
      <td>{first}</td>
      <td>{second}</td>
      <td>{third}</td>
    </tr>
  </tbody>
</table>
)
}

然后这样称呼它

<GenericTable first={name} second={first_test.week_day} third={first.four.three} />

或

<GenericTable first={name} second={test.time} third={another.one.two} />

根据评论更新 1

function GenericTable({ columns }) {
  columnstb = columns.map((column, index) => (<td key={index}>{column}</td>);
return (
<table>
  <tbody>
    <tr>
      {columnstb}
    </tr>
  </tbody>
</table>
)
}

然后这样称呼它

<GenericTable columns={[name, first_test.week_day, first.four.three]} />

【讨论】:

  • 好的,如果它不总是三个 ,我的意思是如果有四个来自某个 api 调用或不同的号码怎么办?
  • @Zygimantas 使用数组代替多列
猜你喜欢
相关资源
最近更新 更多
热门标签