Как отображать данные Dynami c в таблице Material-UI? - PullRequest
1 голос
/ 05 августа 2020

У меня есть API, который возвращает некоторые табличные данные. Мне нужно отобразить эти данные в таблице. Мне неясно, как достичь этой цели.

Предположим, я хочу отобразить поля id и name, хранящиеся в groups. Как я могу показать их в таблице 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>
    )
} 

Обновление:

Как я уже упоминал в комментариях, я выполнил рекомендации из ответов, но я все еще вижу пустая таблица, а в консоли отображается правильное значение.

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>
    )

Это то, что я вижу в браузере:

enter image description here

This is an example of data (groups.data.subtask):

введите описание изображения здесь

Ответы [ 3 ]

2 голосов
/ 05 августа 2020

Я думаю, проблема в том, что вы используете 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>
)
1 голос
/ 05 августа 2020

Я думаю, что это Object.keys(groups).

Это не состояние React, поэтому он не будет повторно отображаться?

Можете ли вы попробовать создать состояние groupKey, а затем использовать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>))
}

Понятно.

1 голос
/ 05 августа 2020

Что-то вроде ниже должно помочь: введите описание изображения здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...