繁体   English   中英

无法使用 React Class Component using TypeScript 在 antd 中添加行

[英]Cannot add row in antd with React Class Component using TypeScript

我正在使用 tsx 文件将数据添加到 antd 表中,但是当我单击具有事件的按钮时无法向其中添加行:“handleAddTicket”。 但是当我更改线路时: const tickets: TicketLine[] = ticketLines; const tickets: TicketLine[] = []; ,该行已成功添加到表中,它不是数组,而是最新的元素。 我不知道为什么它不起作用,但当我记录ticketLines变量时,它显示了正确的数组。

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;

由于您在 render 方法中定义了handleAddTicket ,因此它对陈旧版本的tickets进行了关闭。 所以每次它被调用时,它都是建立在你的tickets的前一个渲染版本之上的。

handleAddTicket这样的事件处理程序通常是组件 class 中的一个单独方法。它不应该通过闭包访问tickets ,而应该只访问 state 中的 ticketLines。

在 class 组件中更新 state 时有一个警告。 参见https://reactjs.org/docs/faq-state.html

所以我会做这样的事情:

  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
        ]
      };
    });
  }

暂无
暂无

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

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