【问题标题】:How to display dynamic data in Material-UI table?如何在 Material-UI 表格中显示动态数据?
【发布时间】:2020-08-05 15:05:12
【问题描述】:

我有返回一些表格数据的 API。我需要在表格中显示这些数据。我不清楚如何实现这个目标。

假设我要显示存储在groups 中的字段idname。如何在 Material-UI 表中显示它们?

请在下面查看我当前的代码。它不会抛出任何错误。但两者都没有显示包含数据的表格。

import '../../App.css';
import React, { useEffect } from 'react'
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import axios from 'axios'
import config from '../../config/config.json';

const useStyles = makeStyles((theme) => ({
    root: {
        width: '100%',
    },
    heading: {
        fontSize: theme.typography.pxToRem(18),
        fontWeight: theme.typography.fontWeightBold,
    },
    content: {
        fontSize: theme.typography.pxToRem(14),
        fontWeight: theme.typography.fontWeightRegular,
        textAlign: "left",
        marginTop: theme.spacing.unit*3,
        marginLeft: theme.spacing.unit*3,
        marginRight: theme.spacing.unit*3
    },
    table: {
        minWidth: 650,
    },
    tableheader: {
        fontWeight: theme.typography.fontWeightBold,
        color: "#ffffff",
        background: "#3f51b5"
    },
    tableCell: {
        background: "#f50057"
    },
    button: {
        fontSize: "12px",
        minWidth: 100
    },
}));


export function Main() {

    const [groups, setGroup] = React.useState('');

    const classes = useStyles();

    const options = {
        'headers': {
            'Authorization': `Bearer ${localStorage.getItem('accessToken')}`
        }
    }

    useEffect(() => {
        axios.get(config.api.url + '/api/test', options)
            .then( (groups) => {
                this.setState({response: groups})
            })
            .catch( (error) => {
                console.log(error);
            })
    }, [])

    return (
        <div className={classes.root}>

            <Grid container spacing={3}>
                <Grid item xs={12} className={classes.content}>
                    <TableContainer component={Paper}>
                        <Table id="split_table" size="small">
                            <TableHead>
                            </TableHead>
                            <TableBody>
                                {Object.keys(groups).map( (row, index) => (
                                    <TableRow key={index} selected="false">
                                        <TableCell>Test</TableCell>
                                        <TableCell>Test</TableCell>
                                    </TableRow>))}
                            </TableBody>
                        </Table>
                    </TableContainer>

                </Grid>    
            </Grid>
        </div>
    )
} 

更新:

正如我在 cmets 中提到的,我遵循了答案中的建议,但我仍然看到一个空表,而我可以在控制台中看到正确的值。

useEffect(() => {
        axios.get(config.api.url + '/api/test', options)
            .then( (groups) => {
                setGroup(groups.data.subtask)
                console.log(groups.data.subtask);
            })
            .catch( (error) => {
                console.log(error);
            })
    }, [])

    return (
        <div className={classes.root}>

            <Grid container spacing={3}>
                <Grid item xs={12} className={classes.content}>
                    <TableContainer component={Paper}>
                        <Table id="split_table" size="small">
                            <TableHead>
                            </TableHead>
                            <TableBody>
                                    {Object.keys(groups).map( (item, index) => (
                                    <TableRow key={index} selected="false">
                                        <TableCell>{item.user_id}</TableCell>
                                        <TableCell>{item.task_name}</TableCell>
                                    </TableRow>))}
                            </TableBody>
                        </Table>
                    </TableContainer>

                </Grid>    
            </Grid>
        </div>
    )

这是我在浏览器中看到的:

这是一个数据示例(groups.data.subtask):

【问题讨论】:

  • 使用 setGroup(groups) 代替 this.setState({response: groups})
  • 我认为这里有问题 setGroup(groups.data.subtask[0])。尝试这样写 setGroup(groups.data.subtask)
  • @AlexAV-dev:我试过了。它不起作用。
  • @AlexAV-dev:请查看我的最新更新,我按照您的要求发布了groups.data.subtask 的示例。
  • 我更新了我的答案,看看吧。问题是你给了我们错误的对象键

标签: javascript reactjs axios material-ui


【解决方案1】:

我认为问题在于您使用this.setState 而不是setGroup

useEffect(() => {
    axios.get(config.api.url + '/api/test', options)
        .then( (groups) => {
            setGroup(groups)
        })
        .catch( (error) => {
            console.log(error);
        })
}, [])

改变你的地图功能

{Object.keys(groups).map( (row, index) => (
  <TableRow key={index} selected="false">
    <TableCell>{row._id}</TableCell>
    <TableCell>{row.user_id}</TableCell>
  </TableRow>))}

import '../../App.css';
import React, { useEffect } from 'react'
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import axios from 'axios'
import config from '../../config/config.json';

const useStyles = makeStyles((theme) => ({
    root: {
        width: '100%',
    },
    heading: {
        fontSize: theme.typography.pxToRem(18),
        fontWeight: theme.typography.fontWeightBold,
    },
    content: {
        fontSize: theme.typography.pxToRem(14),
        fontWeight: theme.typography.fontWeightRegular,
        textAlign: "left",
        marginTop: theme.spacing.unit*3,
        marginLeft: theme.spacing.unit*3,
        marginRight: theme.spacing.unit*3
    },
    table: {
        minWidth: 650,
    },
    tableheader: {
        fontWeight: theme.typography.fontWeightBold,
        color: "#ffffff",
        background: "#3f51b5"
    },
    tableCell: {
        background: "#f50057"
    },
    button: {
        fontSize: "12px",
        minWidth: 100
    },
}));


export function Main() {

    const [groups, setGroup] = React.useState([]);

    const classes = useStyles();

    const options = {
        'headers': {
            'Authorization': `Bearer ${localStorage.getItem('accessToken')}`
        }
    }

useEffect(() => {
        axios.get(config.api.url + '/api/test', options)
            .then( (groups) => {
                setGroup(groups.data.subtask)
                console.log(groups.data.subtask);
            })
            .catch( (error) => {
                console.log(error);
            })
    }, [])

return (
    <div className={classes.root}>

        <Grid container spacing={3}>
            <Grid item xs={12} className={classes.content}>
                <TableContainer component={Paper}>
                    <Table id="split_table" size="small">
                        <TableHead>
                        </TableHead>
                        <TableBody>
                                {Object.keys(groups).map( (item, index) => (
                                <TableRow key={index} selected="false">
                                    <TableCell>{item.user_id}</TableCell>
                                    <TableCell>{item.task_name}</TableCell>
                                </TableRow>))}
                        </TableBody>
                    </Table>
                </TableContainer>

            </Grid>    
        </Grid>
    </div>
)

【讨论】:

  • 不仅使用setState,他还在使用this.setState({response: groups})(设置response状态,而不是groups状态)。
  • @yaya 我认为这不是问题,因为我们无论如何都会将响应保存在状态组中。如果是这样,我可能是错的,请解释我为什么不对:)
  • 没有this.setState({response: groups})groups 变量的值设置为response 状态?
  • 谢谢。现在我可以看到桌子了。但是这个表的内容还是错的,因为我觉得我&lt;Table&gt;...&lt;/Table&gt;里面的代码是错的。我在表格的所有单元格中看到Test,而不是真实数据。
  • @Fluxy 是的,您应该将 &lt;TableCell&gt;Test&lt;/TableCell&gt; 替换为 &lt;TableCell&gt;{row.yourcolname}&lt;/TableCell&gt;
【解决方案2】:

我认为是Object.keys(groups)

不是 React 状态,所以不会重新渲染?

你能不能尝试做一个groupKey状态,然后在groups更新时使用Effect来更新状态。

const [groupKey,setGroupKey] = useState([]);

useEffect(() => {
  setGroupKey(Object.keys(groups));
},[groups]);

在组件中,使用

{groupKey.map((item, index) => (
  <TableRow key={index} selected="false">
    <TableCell>{item.user_id}</TableCell>
    <TableCell>{item.task_name}</TableCell>
  </TableRow>))
}

你明白了。

【讨论】:

  • 你能详细说明你的答案吗? “groupKey 状态”是什么意思?任何示例将不胜感激。谢谢。
  • react 只有在状态发生变化时才会呈现。 Object.keys() 将给出一个不是反应状态的新数组。所以它不会重新渲染?只是一个建议。
  • 我认为你是对的。但我不明白你的例子的某些方面。 [groups] 是什么?
  • @Fluxy 它是 useEffect 的依赖项。 useEffect 将接受两个参数..一个执行副作用的函数和一个依赖数组..当依赖项发生变化时,该函数会再次执行。
  • 需要将初值字符串替换为数组[groupKey,setGroupKey] = useState([]);
【解决方案3】:

以下内容应该会有所帮助:

【讨论】:

  • 我收到错误TypeError: groups.map is not a function
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-11
  • 1970-01-01
  • 2020-07-15
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
相关资源
最近更新 更多