reactjs - Mui-Datatables 函数中的 tableState 导致无限循环

标签 reactjs mui-datatable

React 新手...我正在尝试在 React 函数中设置并保存 Mui-Datatable tableState。当我使用以下代码时,出现以下错误:

错误:超出最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。

如何修复我的代码以免发生这种情况?我将它从类转换为函数,这样我就可以使用钩子(Hook)。

import React, {useEffect, useState} from 'react';
import MUIDataTable from "mui-datatables";
import { MuiThemeProvider } from '@material-ui/core/styles';
import { Typography, Box } from '@material-ui/core';
import MuiDataTableCSS from '../../Styles/MuiDataTable';
import Button from '@material-ui/core/Button';

export default function ProposalTable() {
const [isLoading, setIsLoading] = useState(false);
const [cols, setCols] = useState([]);
const [users, setUsers] = useState([]);
const [currTable, setCurrTable] = useState({});

const options = {
    filterType: 'multiselect',
    responsive: 'standard',
    fixedHeader: true,
    elevation: 1,
    selectableRows: false,
    tableBodyHeight: 'calc(100vh - 200px)',
    print: false,
    resizableColumns: false,
    draggableColumns: {
      enabled: true,
    },
    onTableInit: handleTableInit, 
    onTableChange: handleTableChange,
};

function handleTableInit(action, tableState){
    console.log('handleTableInit: ', tableState);
    setCurrTable({ tableState });
}; 
function handleTableChange(action, tableState){
    setCurrTable({ tableState });
    console.log('handleTableChange: ', tableState);
};

useEffect(() => {
    let cols = [];
    setIsLoading(true); // start the loader
    fetch("/data.json")
    .then(response => response.json())
    .then(data => {
        setIsLoading(false); // stop the loader
        for(var key in data[0]){
            var newKey = key.replace(/_/g, " ");
            cols = [...cols, { name: newKey, label: key}]
        }
        setUsers(data);
        setCols(cols);
    })
    .catch(error => {
        console.log(error);
    })
  .finally(() => {
      setIsLoading(false); // stop the loader
  });
  }, []);

if (isLoading) {
    return <p>Loading...</p>;
}

return (
    <div id="muiDataTable">
        <Typography component="h1" variant="h4" align="center">
            <Box pb="1em">
                Proposals
            </Box>
            <Button style={{ textTransform: 'none' }} onClick={() => handleTableChange('button', currTable)}>Save Table</Button>
        </Typography>
        <MuiThemeProvider theme={MuiDataTableCSS}>
            <MUIDataTable
                data={users}
                columns={cols}
                options={options}/>
        </MuiThemeProvider>
    </div>
)
}

使用类的 Mui-Datatable 示例:https://codesandbox.io/s/github/gregnb/mui-datatables?file=/examples/on-table-init/index.js

Mui-Datatable 示例代码:

import React from 'react';
import ReactDOM from 'react-dom';
import MUIDataTable from '../../src';

class Example extends React.Component {
constructor(props) {
super(props);

this.state = {
  table: {}
};
this.handleTableInit = this.handleTableInit.bind(this);
this.handleTableChange = this.handleTableChange.bind(this);
}

/** onTableInit gives access to initial MuiDataTable state
   *  if the application needs access to internal state prior to
   *  the user performing a table mutation (sort, filter, etc.)
   *  that triggers onTableChange
 */
handleTableInit = (action, tableState) => {
console.log('handleTableInit: ', tableState);
this.setState({ table: tableState });
};

handleTableChange = (action, tableState) => {
  console.log('handleTableChange: ', tableState);
  this.setState({ table: tableState });
};

columns = ['Name', 'Title', 'Location', 'Age', 'Salary'];

data = [
  ['Eli Mejia', 'Commercial Specialist', 'Long Beach', 65, 400000],
  ['Gene Leblanc', 'Industrial Analyst', 'Hartford', 34, 110000],
  ['Danny Leon', 'Computer Scientist', 'Newark', 60, 220000],
  ['Lane Lee', 'Corporate Counselor', 'Cincinnati', 52, 180000],
  ['Jesse Hall', 'Business Analyst', 'Baltimore', 44, 99000],
  ['Danni Hudson', 'Agency Legal Counsel', 'Tampa', 37, 90000],
  ['Terry Macdonald', 'Commercial Specialist', 'Miami', 39, 140000],
  ['Justice Mccarthy', 'Attorney', 'Tucson', 26, 330000],
  ['Silver Carey', 'Computer Scientist', 'Memphis', 47, 250000],
  ['Franky Miles', 'Industrial Analyst', 'Buffalo', 49, 190000],
  ['Glen Nixon', 'Corporate Counselor', 'Arlington', 44, 80000],
  ['Gabby Strickland', 'Business Process Consultant', 'Scottsdale', 26, 45000],
  ['Mason Ray', 'Computer Scientist', 'San Francisco', 39, 142000],
];

options = {
  filter: true,
  selectableRows: 'multiple',
  filterType: 'dropdown',
  responsive: 'standard',
  rowsPerPage: 10,
  download: false, // hide csv download option
  onTableInit: this.handleTableInit,
  onTableChange: this.handleTableChange,
};

render() {
  return <MUIDataTable title={'ACME Employee list'} data={this.data} columns={this.columns} options={this.options} />;
  }
}

export default Example;

最佳答案

您可以根据它指定要更新表状态的更改操作,以避免无限循环

    onTableChange: (action, tableState) => {
            switch (action) {
                case 'changePage':
                    setCurrTable({ tableState });
                    break;
                case 'sort':
                    setCurrTable({ tableState });
                    break;
                default:
                    console.log('action not handled.');
            }
       }

关于reactjs - Mui-Datatables 函数中的 tableState 导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66604608/

相关文章:

javascript - 卸载 setState 警告,即使组件已安装

javascript - ES6 : constructor can't declare as arrow function?

javascript - 如何从函数调用中读取 Promise 解析值

angular - NgxMuiDatatables 无法使用 --aot 编译

javascript - MUI-Datatable 可扩展行

node.js - 使用 puppeteer 生成包含多个页面的 PDF

css - 如何在 react-static 中使用 node-sass

javascript - 我无法访问 react 中的数据

reactjs - 如何在React mui-Datatable中完成customRender

reactjs - 选择数据表中的行(mui-datatable)