首页 > 解决方案 > 如何向表中添加键

问题描述

出现此错误:- 第一次使用 react 和 react-table。使用此代码:-

render() {
        const itemData = this.state.itemData;

        const columns = [{
            Header: 'ID',
            Cell: props => <span key={props.value}>{props.value}</span>,
            accessor: 'ID',

        }, {
            Header: 'Name',
            accessor: 'name'

        },{
            Header: 'Description',
            accessor: 'description'

        }, {
            id: 'price', // Required because our accessor is not a string
            Header: 'Price',
            accessor: d => d.price // Custom value accessors!
        }]


        console.log(itemData)
        console.log(columns)
        return (
            <div>
                <CreateItemModal getItems={this.getItems}/>
                {_.map(itemData, () => (
                <ReactTable key={itemData.ID}
                    data={itemData}
                    resolveData={data => data.map(row => row)}
                    columns={columns}
                />
                ))}
            </div>
        );
    }

收到此错误:-

index.js:2178 Warning: Each child in an array or iterator should have a unique "key" prop.

Check the render method of `ItemDashboard`. 
    in ReactTable (at itemDashboard.js:77)
    in ItemDashboard (at App.js:28)
    in div (created by Segment)
    in Segment (at App.js:22)
    in App (at index.js:9)

ItemData 是这样的数组:-

ID:"78edeef0-6105-11e8-a64e-25cbecc86b8a"
description:"hdhdhdhdhd"
name:"this"
price:"88888"

我似乎找不到合适的文档来告诉我如何为每个表行添加键。你能为我指出正确的方向吗?

初始化代码:-

class ItemDashboard extends Component {

    constructor(props){
        super(props)
        this.state = {itemData: {}, item: {}, modalOpen: false}
        this.getItems = this.getItems.bind(this);

    }

    getItems(){
        API.get(apiName, path).then(response => {
            console.log(response)
            this.setState({
                itemData: response.data
            });
        });
    }

标签: javascriptreactjsreact-table

解决方案


You are trying to render a table for each property of itemData. You should just pass your itemData to the react-table:

return (
  <div>
      <CreateItemModal getItems={this.getItems}/>
      <ReactTable
          data={itemData}
          columns={columns}
      />
  </div>
);

resolveData is being used to reshape the data, so I guess resolveData={data => data.map(row => row)} is doing nothing.


推荐阅读