reactant设计可编辑表

but5z9lq  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(416)

因此,我跟踪这个文档来创建一个可编辑的行;这是一个用于ant design中react的css库,我被困在以下几个方面:
我如何通过改变了的那一排 newData[index] 去一个onchange事件?
如何将一组数据行更新到后端restapi?我设法使用ant design中的表单创建数据,但我不知道如何使用可编辑行更新它
仅供参考,后端工作与 Postman 完美:创建,更新,删除
如何获取此代码的id? axios.put("/api/product/update/:id" 我试着把它换掉 id${id} , ${index} , ${products[index]} (使用模板文字)但它不起作用。
以下是完整代码:

import React from 'react';
import axios from 'axios';
import { Table, Input, InputNumber, Popconfirm, Form } from 'antd';

const FormItem = Form.Item;
const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  getInput = () => {
    if (this.props.inputType === 'number') {
      return <InputNumber />;
    }
    return <Input />;
  };

  render() {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      ...restProps
    } = this.props;
    return (
      <EditableContext.Consumer>
        {(form) => {
          const { getFieldDecorator } = form;
          return (
            <td {...restProps}>
              {editing ? (
                <FormItem style={{ margin: 0 }}>
                  {getFieldDecorator(dataIndex, {
                    rules: [{
                      required: true,
                      message: `Please Input ${title}!`,
                    }],
                    initialValue: record[dataIndex],
                  })(this.getInput())}
                </FormItem>
              ) : restProps.children}
            </td>
          );
        }}
      </EditableContext.Consumer>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = { products: [], editingKey: '' };
    this.columns = [
      {
        title: 'Product Name',
        dataIndex: 'productname',
        width: '25%',
        editable: true,
      },
      {
        title: 'OS',
        dataIndex: 'os',
        width: '10%',
        editable: true,
      },
      {
        title: 'Category',
        dataIndex: 'category',
        width: '15%',
        editable: true,
      },
      {
        title: 'Model',
        dataIndex: 'model',
        width: '20%',
        editable: true,
      },
      {
        title: 'Serial Number',
        dataIndex: 'serialnumber',
        width: '20%',
        editable: true,
      },
      {
        title: 'Operation',
        dataIndex: 'operation',
        width: '10%',
        render: (text, record) => {
          const editable = this.isEditing(record);
          return (
            <div>
              {editable ? (
                <span>
                  <EditableContext.Consumer>
                    {form => (
                      <a
                        href="javascript:;"
                        onClick={() => this.save(form, record.id)}
                        style={{ marginRight: 8 }}
                      >
                        Save
                      </a>
                    )}
                  </EditableContext.Consumer>
                  <Popconfirm
                    title="Sure to cancel?"
                    onConfirm={() => this.cancel(record.id)}
                  >
                    <a>Cancel</a>
                  </Popconfirm>
                </span>
              ) : (
                  <a onClick={() => this.edit(record.id)}>Edit</a>
                )}
            </div>
          );
        },
      },
    ];
  }

  handleCategoryChange = event => { this.setState({ category: event.target.value }) }
  handleProductNameChange = event => { this.setState({ productname: event.target.value }) }
  handleOsNameChange = event => { this.setState({ os: event.target.value }) }
  handleModelchange = event => { this.setState({ model: event.target.value }) }
  handleSerialnumberChange = event => { this.setState({ serialnumber: event.target.value }) }
  handlePriceChange = event => { this.setState({ price: event.target.value }) }
  handleEquipmentChange = event => { this.setState({ equipment_condition: event.target.value }) }
  handleDetailChange = event => { this.setState({ detail: event.target.value }) }
  handleImageChange = event => { this.setState({ image: event.target.value }) }

  handleSubmit = event => {
    event.preventDefault();
    axios.put(`/api/product/update/:id`,
      {
        category: this.state.category,
        productname: this.state.productname,
        os: this.state.os,
        serialnumber: this.state.serialnumber,
        model: this.state.model,
        price: this.state.price,
        equipment_condition: this.state.equipment_condition,
        detail: this.state.detail,
        image: this.state.image
      })
  }

  componentDidMount() {
    axios.get('/api/product').then(res => {
    this.setState({ products: res.data });
    });
  }

  isEditing = (record) => {
    return record.id === this.state.editingKey;
  };

  edit(id) {
    console.log('products', this.state.products.id);
    // console.log('recordid', record.id);
    this.setState({ editingKey: id });
  }

  save(form, id) {
    console.log('key', id)
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const newData = [...this.state.products];
      const index = newData.findIndex(item => id === item.id); 
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row, });      
        this.setState({ products: newData, editingKey: '' });
        console.log('newData', newData[index]) // data I want to update to API
        console.log('category', newData[index].category) // category

      } else {
        newData.push(this.state.products);
        this.setState({ products: newData, editingKey: '' });
      }
    });
  }

  cancel = () => {
    this.setState({ editingKey: '' });
  };

  render() {
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };

    const columns = this.columns.map((col) => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === 'serialnumber' ? 'number' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });

    return (
      <Table
        rowKey={this.state.id}
        components={components}
        bordered
        dataSource={this.state.products}
        columns={columns}
        rowClassName="editable-row"
      />
    );
  }
}

export default EditableTable;

更新:所以我尝试将axios放在save方法中,如下所示:

save(form, id) {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const newData = [...this.state.products];
      const index = newData.findIndex(item => id === item.id); 
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row, });      
        this.setState({ products: newData, editingKey: '' });
        console.log('newData', newData[index]) // data I want to update to API
        console.log('index', index) // index adalah index array
        console.log('id', id) // id adalah nomor index dalam tabel database, jangan sampai tertukar

        console.log('category', newData[index].category)
        console.log('productname', newData[index].productname)
        console.log('os', newData[index].os)
        console.log('serialnumber', newData[index].serialnumber)
        console.log('model', newData[index].model)
        console.log('detail', newData[index].detail)
        axios.put(`/api/product/update/:${id}`,
          {
            category: newData[index].category,
            productname: newData[index].productname,
            os: newData[index].os,
            serialnumber: newData[index].serialnumber,
            model: newData[index].model,
            price: newData[index].price,
            equipment_condition: newData[index].equipment_condition,
            detail: newData[index].detail,
            image: newData[index].image
          })

      } else {
        newData.push(this.state.products);
        this.setState({ products: newData, editingKey: '' });
      }
    });

它不会更新数据库中的数据。

1cklez4t

1cklez4t1#

所以有一个奇怪的语法,我必须从url api中删除。注意网址的细微细节;我从后端/节点的控制台日志中注意到:

axios.put(`/api/product/update/${id}`,
          {
            category: newData[index].category,
            productname: newData[index].productname,
            os: newData[index].os,
            serialnumber: newData[index].serialnumber,
            model: newData[index].model,
            price: newData[index].price,
            equipment_condition: newData[index].equipment_condition,
            detail: newData[index].detail,
            image: newData[index].image
          })

相关问题