Home > Software engineering >  Cannot add row in antd with React Class Component using TypeScript
Cannot add row in antd with React Class Component using TypeScript

Time:01-05

I'm using a tsx file to add data into antd table but cannot add rows into it when I click on the button which have event: "handleAddTicket". But when I changed the line: const tickets: TicketLine[] = ticketLines; to const tickets: TicketLine[] = [];, the row was added into the table successfully, it was not an array, but the newest element . I don't know why it doesn't work though when I logged the ticketLines variable, it showed the correct array.

import * as React from 'react';
import './index.less';

import { Button, Card, Col, Dropdown, Menu, Row, Table } from 'antd';
import { inject, observer } from 'mobx-react';
import OrderStore from '../../stores/orderStore';
import Stores from '../../stores/storeIdentifier';
import AppComponentBase from '../../components/AppComponentBase';

export interface IOrderProps {
  orderStore: OrderStore;
}

export interface IOrderState {
  ticketLines: TicketLine[];
}

export interface TicketLine {
  key: number,
  policyObject: any,
  ticketType: string,
  ticketAmount: 1,
  region: any,
  areaWindowTimeId: 0,
  ticketComboPrice: number,
  actionDelete: boolean  
}

@inject(Stores.OrderStore)
@observer
class Order extends AppComponentBase<IOrderProps, IOrderState> {
  async componentDidMount() {
    await this.getAll();
  }

  async getAll() {
    await this.props.orderStore.initialize();
  }

  constructor(props:IOrderProps) {
    super(props);
    this.state = {
      ticketLines: []
    };
  }

public render() {
  const { ticketComboOutput, policyObjectOutput } = this.props.orderStore;
  const {ticketLines} = this.state;

  const tickets: TicketLine[] = ticketLines;
  const handleAddTicket = (item:any, menu:any) => {
    const ticket: TicketLine = {
    key: item.id,
    policyObject: policyObjectOutput[0].name,
    ticketType: item.description,
    ticketAmount: 1,
    region: item.areas[0].name,
    areaWindowTimeId: 0,
    ticketComboPrice: item.ticketComboPrice.price,
    actionDelete: true    
    }
    tickets.push(ticket);
    // console.log(tickets);
    this.setState({ticketLines: tickets});
  };
  console.log(ticketLines);
  
  var items = policyObjectOutput.map(p =>
      <Menu.Item key={p.id}>
        <p>{p.name} - Giảm {p.policyObjectDiscount.discountPercent * 100}%</p>
      </Menu.Item>
    );
    const menu = (
      <Menu>{items}</Menu>
    );
    const columns = [
      {
        title: 'Đối tượng miễn giảm',
        dataIndex: 'policyObject',
        key: 'policyObject',
      },
      {
        title: 'Loại vé',
        dataIndex: 'ticketType',
        key: 'ticketType',
      },
      {
        title: 'Số lượng',
        dataIndex: 'ticketAmount',
        key: 'ticketAmount',
      },
      {
        title: 'Khu vực',
        dataIndex: 'region',
        key: 'region',
      },
      {
        title: 'Khung giờ',
        dataIndex: 'areaWindowTimeId',
        key: 'areaWindowTimeId',  
      },
      {
        title: 'Thành tiền',
        dataIndex: 'ticketComboPrice',
        key: 'ticketComboPrice'
      },
      {
        title: 'Xóa',
        dataIndex: 'actionDelete',
        key: 'actionDelete'
      } 
    ];

    return (
      <>
        <Row gutter={16}>
          {ticketComboOutput.map(
            item =>
              <Card className='ticketCombo' key={item.id} title={item.name} style={{ width: 300 }}>
                <p>Thông tin: {item.description}</p>
                <p>Giá vé: {item.ticketComboPrice.price}</p>
                <Row style={{'display': 'flex', 'justifyContent':'space-between'}}>
                  <Col>Khu vực:</Col>
                  <Col>
                    <ul> {
                      item.areas.map(a => <li key={a.id}>{a.name}</li>)
                    }</ul>
                  </Col>
                </Row>
                <Row style={{'display': 'flex', 'justifyContent':'space-between'}}>
                  <Col>
                    <Dropdown overlay={menu}>
                      <a>Đối tượng</a>
                    </Dropdown>
                  </Col>
                  <Col>
                    <Button 
                    onClick={()=> handleAddTicket(item, menu)}
                    title="Chọn">Chọn</Button>
                  </Col>
                </Row>
              </Card>
          )}
        </Row>
        <Table dataSource={ticketLines} columns= {columns}/>              
      </>
    )

  }
}
export default Order;

CodePudding user response:

Since you defined handleAddTicket within the render method, it has a closure over a stale version of tickets. So every time it's called, it's building on top of the previous render's version of your tickets.

An event handler like handleAddTicket would usually be a separate method in your component class. And instead of accessing tickets via a closure, it should just access ticketLines in state.

There is a caveat when updating state in a class component. See https://reactjs.org/docs/faq-state.html

So I would do something like this:

  private handleAddTicket (item:any, menu:any) {
    const ticket: TicketLine = {
      key: item.id,
      policyObject: policyObjectOutput[0].name,
      ticketType: item.description,
      ticketAmount: 1,
      region: item.areas[0].name,
      areaWindowTimeId: 0,
      ticketComboPrice: item.ticketComboPrice.price,
      actionDelete: true    
    }

    this.setState(state => {
      return {
        ...state,
        ticketLines: [
          ...state.ticketLines,
          ticket
        ]
      };
    });
  }
  • Related