简体   繁体   English

将JSON数据格式化为表React.js

[英]Formatting json data into table React.js

I have this state defined: 我已定义此状态:

 constructor(props){
        super(props);

        this.state = {
            open: false,
            customers:[],
            customer:{},
            products:[],
            product:{},
            orders:[],
            order:{},
            newForm:true,
            phoneNumbererror:null,
            shop:this.props.salon,
            value:'a',
            showTab:'none',
            slideIndex: 0,

        };
    }

With the following function which contains a fetch, I recieve an array of objects with responseData. 通过以下包含提取的函数,我收到了带有responseData的对象数组。

getHistory(){
        console.log("Log antes del fetch de customer id");
        console.log(this.state.customer._id);
        fetch(
            DOMAIN+'/api/orders/customer/'+this.state.customer._id, {
                method: 'get',
                dataType: 'json',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'Authorization':'Bearer '+this.props.token
                }
            })
            .then((response) =>
            {
                return response.json();
            })
            .then((responseData) => {
                let orders = responseData.map((order) => {
                    return order.orderStatusChange ? Object.assign({}, order, {
                        status: order.orderStatusChange[0].status
                    }) : order;
                });
                this.setState({orders:orders});
                console.log("Log del responseData");
                console.log(responseData);
                console.log(responseData.orderStatusChange[0]);

            })
            .catch(function() {
                console.log("error");
            });
    }

This function is called in handleCellClick , where I pass some data from the consumer, such as the ID: handleCellClick调用此函数,在这里我从使用者传递一些数据,例如ID:

handleCellClick(y,x,row){
        this.setState({
            open:true,
            slideIndex: 0,
            newForm:false,
            customer:{...row}
        });
        this.getProfiles();
        this.getHistory();

    }

The JSON object obtained from the fetch and kept within this.state.orders looks like this: 从获取中获取并保存在this.state.orders的JSON对象如下所示:

(29) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:
created:"2017-07-06T15:58:07.958Z"
customer:"59561f3f1d178e1966142ad7"
lastModified:"2017-07-06T15:58:07.958Z"
orderList:[]
orderStatusChange:Array(1)
0:{status: "5", comments: "Creado en back antes de pagar", _id: "595e5e0f60fbf65149916b7c", created: "2017-07-06T15:58:07.958Z"}
length:1
__proto__:Array(0)
shop:"59108159bc3fc645704ba508"
totalAmount:4000
__v:0
_id:"595e5e0f60fbf65149916b7b"
__proto__:Object

As shown previously in the fetch, with this line this.setState({orders:responseData}) I can pass orders to the table where I want the id, date, status and price to be displayed: 如之前的提取中所示,使用这一行this.setState({orders:responseData})我可以将orders传递到要显示ID,日期,状态和价格的表格:

<DataTables
     height={'auto'}
     selectable={false}
     showRowHover={true}
     columns={HISTORY_TABLE_COLUMNS}
     data={this.state.orders}
     showCheckboxes={false}
     rowSizeLabel="Filas por página"
         />

The table called is: 调用的表是:

    const HISTORY_TABLE_COLUMNS = [
    {
        key: '_id',
        label: 'Número de pedido',
        style:{width: '37%'}
    }, {
        key: 'created',
        label: 'Fecha del pedido',
        style:{width: '33%'}
    }, {
        key: 'status',
        label: 'Estado',
        style:{width: '13%'}
    }, {
        key: 'totalAmount',
        label: 'Total',
        style:{width: '17%'}
    }
];

How can I format the price (totalAmount) to have 2 decimals and print next to it the € symbol? 如何格式化价格(totalAmount)为2位小数并在其旁边打印€符号?

CAPTURE FOR BETTER UNDERSTANDING 捕捉以便更好地理解

While iterating data in table please do the following. 在迭代表中的数据时,请执行以下操作。

totalAmount.toFixed(2) + " €"

Update: I would suggest this change should be done from backend, But any how for now you can handle it in map iterator where you are setting orders like following 更新:我建议应该从后端进行此更改,但是现在无论如何,您都可以在map迭代器中处理此操作,在该迭代器中您可以像下面这样设置订单

const currencyToAppend = ' €';

    let orders = responseData.map((order) => {
        return order.orderStatusChange ? Object.assign({}, order, {
          status: order.orderStatusChange[0].status
        },{
            totalAmount: order.totalAmount.toFixed(2) + currencyToAppend
        }) : Object.assign({}, order, {
            totalAmount: order.totalAmount.toFixed(2) + currencyToAppend
        });
    });

I hope this will solve your problem. 我希望这能解决您的问题。

This solution works fine with node module material-ui-datatables version 0.18.0 该解决方案与节点模块material-ui-datatables版本0.18.0配合使用时效果很好

You can use render method in column settings to work on the column data. 您可以在列设置中使用渲染方法来处理列数据。

const currencyToAppend = '€';
const HISTORY_TABLE_COLUMNS = [
  {
    ....
  }, {
    ....
  }, {
    key: 'totalAmount',
    label: 'Total',
    style:{width: '17%'}
    render: (amount, all) => {
        console.log(amount);
        console.log(all);
        return amount + ' ' + currencyToAppend;
    }
  }
];

To complement @dev's answer, I'd suggest to have render the cell as a function as that gives you more control 为了补充@dev的答案,我建议将单元格作为函数渲染,因为它可以为您提供更多控制权

Check out the codesandox demo https://codesandbox.io/s/0VVwq645L 查看codeandox演示https://codesandbox.io/s/0VVwq645L

const HISTORY_TABLE_COLUMNS = [
  {
    key: "_id",
    label: "Número de pedido",
    style: { width: "37%" },
    value: item =>
      <code>
        {item._id}
      </code>
  },
  {
    key: "created",
    label: "Fecha del pedido",
    style: { width: "33%" },
    value: item => <Time value={item.created} />
  },
  {
    key: "status",
    label: "Estado",
    style: { width: "13%" },
    value: item =>
      <span>
        {item.status}
      </span>
  },
  {
    key: "totalAmount",
    label: "Total",
    style: { width: "17%" },
    value: item => <Amount value={item.totalAmount} currency="€"} />
  }
];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM