将项目添加到数组后刷新页面

时间:2019-12-17 09:50:12

标签: reactjs

有一个具有默认值的数组,并且使用Delta,表列表将项目添加到该数组中。当立即添加一行时,表的行数返回默认值,为什么?

App.js

import React, {Component, Fragment} from 'react';
import {TableData, RegForm} from './Layouts'


class App extends Component {
    state = {
        productList: [
            {id: 11, name: 'CD', price: '2000', describe: 'Educational'},
            {id: 24, name: 'Pen', price: '3500', describe: 'Design'},
            {id: 83, name: 'Pencil', price: '2500', describe: 'Design'}
        ],
    };

    handleDeleteByIndex = index => {
        const product = this.state.productList;
        product.splice(index, 1);
        this.setState({productList: product});
    };

    handleInsertToList = (e) => {
        const product = this.state.productList;
        product.push(e);
        this.setState({productList: product});

    };

    render() {
        const {productList} = this.state;
        return (
            <Fragment>
                <RegForm onInsertRow={this.handleInsertToList}/>
                <TableData rows={productList} onDeleteRow={this.handleDeleteByIndex}/>

            </Fragment>
        );

    }
}

export default App

完整代码:enter link description here

1 个答案:

答案 0 :(得分:2)

由于提交表单,页面正在刷新,因此所有内容均被重置。

Layouts/RegForm.js中,您需要阻止表单的默认操作:

<form
  className={classes.root}
  noValidate
  autoComplete="off"
  onSubmit={(e) => {
    e.preventDefault() // <-- Add this
    props.onInsertRow({
      id: id,
      name: name,
      price: price,
      describe: describe
    });
  }}
>

我希望这会有所帮助。

相关问题