【问题标题】:Reat-Bootstrap-Table: Each child in a list should have a unique "key" propReact-Bootstrap-Table:列表中的每个孩子都应该有一个唯一的“关键”道具
【发布时间】:2020-08-11 16:17:09
【问题描述】:

我一直在尝试创建一个 react-bootstrap-table2,但我收到以下警告:列表中的每个孩子都应该有一个唯一的“关键”道具。

这是我的代码:

export const columns = [
  {
    dataField: "timestamps",
    text: "Timestamp",
  },
];

class Table extends Component {
  constructor(props) {
    super(props);
    this.state = { timestamps: [] };
  }
  componentDidMount() {
    const database = db.ref().child("timestamped_measures");
    database.on("value", (ts_measures) => {
      const timestamps = [];
      const columns = [{ dataField: "timestamps", text: "Timestamp" }];
      ts_measures.forEach((ts_measure) => {
        timestamps.push(ts_measure.val().timestamp);
      });
      console.log(timestamps);
      this.setState((prevState) => {
        return { timestamps: [...prevState.timestamps, ...timestamps] };
      });
    });
  }

  render() {
    return (
      <div className="App">
        <BootstrapTable
          keyField="timestamps"
          data={this.state.timestamps.map((item) => ({ item }))}
          columns={columns}
          pagination={paginationFactory()}
        />
      </div>
    );
  }
}
export default Table;

Here is the console with the list of data I am trying to display

所以我的问题是如何给列表中的每个孩子一个唯一的键。

任何帮助将不胜感激!

【问题讨论】:

标签: javascript reactjs firebase firebase-realtime-database react-bootstrap-table


【解决方案1】:

您传递的是整数数组,而不是具有“时间戳”属性的对象数组。

export const columns = [
 {
   dataField: "timestamp",
   text: "Timestamp",
 },
];

class Table extends Component {
  constructor(props) {
   super(props);
   this.state = { timestamps: [] };
  }
  
componentDidMount() {
const database = db.ref().child("timestamped_measures");
database.on("value", (ts_measures) => {
  const timestamps = [];
  ts_measures.forEach((ts_measure) => {
    timestamps.push({ timestamp: ts_measure.val().timestamp });
  });
  console.log(timestamps);
  this.setState((prevState) => {
    return { timestamps: [...prevState.timestamps, ...timestamps] };
  });
});
}

 render() {
    return (
      <div className="App">
        <BootstrapTable
          keyField="timestamp"
          data={this.state.timestamps}
          columns={columns}
          pagination={paginationFactory()}
         />
       </div>
    );
    }
  }
 export default Table;

【讨论】:

    【解决方案2】:

    您的keyField 应该设置为dataField(key) 而不是timestamps(value)。此外,不需要数据映射。

    https://react-bootstrap-table.github.io/react-bootstrap-table2/docs/table-props.html#keyfield-required-string

    <BootstrapTable
       keyField="dataField"
       data={this.state.timestamps}
       columns={columns}
       pagination={paginationFactory()}
    />
    

    【讨论】:

      猜你喜欢
      • 2020-01-24
      • 1970-01-01
      • 2023-02-21
      • 2019-08-21
      • 2020-03-01
      • 1970-01-01
      • 2021-09-23
      • 2021-02-19
      相关资源
      最近更新 更多