提交表格后刷新表格

时间:2020-07-15 11:44:35

标签: reactjs material-ui mui-datatable

我正在通过使用材料ui和mui-datatable在reactjs中使用表构建简单的Crud应用程序。 我的在componentDidMount()中使用fetch()来用处理过的数据填充表。 我的”通过fetch()提交数据。我应该如何刷新或重新加载我的数据?由于数据是在服务器端修改的,因此无法使用输入中的值来更改表的状态。任何帮助>

dummyTableComponent

import React, { Component } from 'react'
import MUIDataTable from "mui-datatables";
import EditIcon from '@material-ui/icons/Edit';
import DeleteIcon from '@material-ui/icons/Delete';
import Chip from '@material-ui/core/Chip';
import Button from '@material-ui/core/Button';
import dummyDialogForm from './dummyDialogForm';

import { createMuiTheme, MuiThemeProvider, withStyles } from '@material-ui/core/styles';

class dummyTableComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {
             data: [],
 
            error: null
        };

    }
    getData(){
        fetch('http://localhost:8080/getAll',{
            headers: {
                Authorization: 'Bearer eyJhbGciOiJIUzUxMiJ9....'
            }})
            .then(response => response.json())
            // .then(response => {
            //     console.log(response);
            // })
            .then(data => this.setState({ data }))
            .catch((error) => {
                console.error('Error:', error);
            });

        console.log(this.state);
    }




    componentDidMount() {
        this.getData()

    }

  getMuiTheme = () => createMuiTheme({
    overrides: {
      MUIDataTable: {
        root: {
        },
        paper: {
          boxShadow: "none",
        }

      },
      MUIDataTableBodyRow: {
        root: {
          '&:nth-child(odd)': {
            backgroundColor: '#fcfeff'
          }
        }
      },
      MUIDataTableBodyCell: {
      }
    }
  })

  render() {

  const columns = [
           {
            name: "id",
            label: "ID",
            options: {
             filter: true,
             sort: true,
             sortDirection:'desc',
            }
           },
           {
            name: "description",
            label: "description",
            options: {
             sort: true,
            }
           },
            {
          name: "name",
          label: "name",
          options: {
              sort: true,
          }
            },

          {
            name: "perInhabitantValue",
            label: "perInhabitantValue",
            options: {
             filter: true,
             sort: true,
            }
           },
           {
            name: "value",
            label: "value",
            options: {
             filter: true,
             sort: true,
            }
           },
          ];

  const {data} = this.state;

  const options = {
            filterType: 'multiselect',
            fixedHeader: true,
            };

    return (
        <React.Fragment>
            <MuiThemeProvider theme={this.getMuiTheme()}>
                <AddAuction/>
                <MUIDataTable
                      title="title"
                      data={data}
                      columns={columns}
                      options={options}
                    />
            </MuiThemeProvider>

            n>
        </React.Fragment>
    )
  }
}


export default Example

dummyDialogForm

import React from 'react';
import ReactDOM from 'react-dom';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogContent from '@material-ui/core/DialogContent';
import DialogActions from '@material-ui/core/DialogActions';
import TextField from '@material-ui/core/TextField';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';


import AddCircleOutlineIcon from '@material-ui/icons/AddCircleOutline';

class dummyDialogForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            values: {
                auctionPropertyTypeId: 1,
                description: "string",
                inHouse: true,
                interCommunityRelation : true,
                name: "pp_test",
                rfid: true
            },
            isSubmitting: false,
            isError: false,
            open: false
        };
    }


    handleInputChange = e =>
        this.setState({
            values: { ...this.state.values, [e.target.name]: e.target.value }
        });

    submitForm = e => {
        // console.warn(this.state)
        e.preventDefault();
        this.setState({ isSubmitting: true });
        fetch("http://localhost:8080/setData", {
            method: "POST",
            body: JSON.stringify(this.state.values),
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwiaWF0IjoxNTk0MzY4MTE5LCJleHAiOjE1OTUyMzIxMTl9.-Y6rl0vOhPCg0_ZaPoUCmoGuhZ-j5uETSs-H4bykn4QHg_3Cx2dFaHU6PFAOWAi8AdB6qu2TA18KWgVwAL2UaQ"
            }
        })
            .then(res => {
                this.setState({ isSubmitting: false });
                return res.json();
            })
            .then(data => {
                console.log(data);
                !data.hasOwnProperty("error")
                    ? this.setState({ message: data.success })
                    : this.setState({ message: data.error, isError: true });
            })
    }

    openDialog() {
        this.setState({ open: true });
    }
    closeDialog() {
        this.setState({ open: false });
    }


    render() {
        const actions = [
            <Button color="primary" onClick={this.closeDialog.bind(this)}>cancel</Button>,
            <Button color="primary" onClick={this.submitForm} type="submit">submit</Button>
        ];

        return (

            <div>
                <Button variant="outlined" color="primary"onClick={this.openDialog.bind(this)}><AddCircleOutlineIcon  color="primary"></AddCircleOutlineIcon> Przetarg </Button>
                <Dialog open={this.state.open} fullScreen>
                    <DialogTitle>Przetarg</DialogTitle>
                    <DialogContent>
                        <form onSubmit={this.submitForm}>
                                <TextField
                                    
                                    name="description"
                                    id="description"
                                    label="opis"
                                    value={this.state.values.email}
                                    onChange={this.handleInputChange}
                                    title="opis"
                                    required
                                />
                        </form>
             
                    </DialogContent>
                    <DialogActions>
                        {actions}
                    </DialogActions>
                </Dialog>
            </div>
        );
    }
}

export default dummyDialogForm

1 个答案:

答案 0 :(得分:1)

在两个组件的最接近的父组件中,创建一个refreshTable()函数以刷新服务器中的数据。

然后将此功能作为道具传递给需要触发它的任何子组件,例如:

<dummyDialogForm refreshTable={this.refreshTable} />

然后,在dummyDialogForm中,提交数据后,您就可以

this.props.refreshTable()

这也意味着这部分:

getData(){
        fetch('http://localhost:8080/getAll',{

不应再位于dummyTableComponent中。它应该在父组件中,并且数据应作为道具传递到dummyTableComponent。然后,您将拥有一个更健壮的体系结构,其中父组件是控制器,所有逻辑都集中在一个地方,兄弟子组件仅关心显示父控制器传递给它们的任何道具。