Хотите заполнить динамические c данные для строк и столбцов из состояния в сворачиваемой таблице с использованием пользовательского интерфейса материала для React. js - PullRequest
0 голосов
/ 14 июля 2020

Я использую сворачиваемую таблицу UI материала: https://material-ui.com/components/tables/#table

Я хочу показать динамические c данные в заголовке и строках и хочу повторить заголовок и строки, чтобы если я нажму на любую строку (Dynami c), она схлопнется.

Я хочу показать данные из этого api в таблице: http://wms-api.martoo.com/api/wms-orders

В настоящее время stati c данные отображаются, но я не могу показать данные dyami c из redux store.

import React, {useEffect} from 'react';
import { connect } from "react-redux";
import PropTypes from 'prop-types';
import {homeActions} from '../../store/home/actions'
import { makeStyles } from '@material-ui/core/styles';
import Box from '@material-ui/core/Box';
import Collapse from '@material-ui/core/Collapse';
import IconButton from '@material-ui/core/IconButton';
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 Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import KeyboardArrowDownIcon from '@material-ui/icons/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@material-ui/icons/KeyboardArrowUp';

const useRowStyles = makeStyles({
  root: {
    '& > *': {
      borderBottom: 'unset',
    },
  },
});
function createData(name, calories, fat, carbs, protein, price) {
    return {
      name,
      calories,
      fat,
      carbs,
      protein,
      price,
      history: [
        { date: '2020-01-05', customerId: '11091700', amount: 3 },
        { date: '2020-01-02', customerId: 'Anonymous', amount: 1 },
      ],
    };
  }
  
  function Row(props) {
    const { row } = props;
    const [open, setOpen] = React.useState(false);
    const classes = useRowStyles();
  
    return (
      <React.Fragment>
        <TableRow className={classes.root}>
          <TableCell>
            <IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)}>
              {open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
            </IconButton>
          </TableCell>
          <TableCell component="th" scope="row">
            {row.name}
          </TableCell>
          <TableCell align="right">{row.calories}</TableCell>
          <TableCell align="right">{row.fat}</TableCell>
          <TableCell align="right">{row.carbs}</TableCell>
          <TableCell align="right">{row.protein}</TableCell>
        </TableRow>
        <TableRow>
          <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={6}>
            <Collapse in={open} timeout="auto" unmountOnExit>
              <Box margin={1}>
                <Typography variant="h6" gutterBottom component="div">
                  History
                </Typography>
                <Table size="small" aria-label="purchases">
                  <TableHead>
                    <TableRow>
                      <TableCell>Date</TableCell>
                      <TableCell>Customer</TableCell>
                      <TableCell align="right">Amount</TableCell>
                      <TableCell align="right">Total price ($)</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {row.history.map((historyRow) => (
                      <TableRow key={historyRow.date}>
                        <TableCell component="th" scope="row">
                          {historyRow.date}
                        </TableCell>
                        <TableCell>{historyRow.customerId}</TableCell>
                        <TableCell align="right">{historyRow.amount}</TableCell>
                        <TableCell align="right">
                          {Math.round(historyRow.amount * row.price * 100) / 100}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </Box>
            </Collapse>
          </TableCell>
        </TableRow>
      </React.Fragment>
    );
  }
  
  Row.propTypes = {
    row: PropTypes.shape({
      calories: PropTypes.number.isRequired,
      carbs: PropTypes.number.isRequired,
      fat: PropTypes.number.isRequired,
      history: PropTypes.arrayOf(
        PropTypes.shape({
          amount: PropTypes.number.isRequired,
          customerId: PropTypes.string.isRequired,
          date: PropTypes.string.isRequired,
        }),
      ).isRequired,
      name: PropTypes.string.isRequired,
      price: PropTypes.number.isRequired,
      protein: PropTypes.number.isRequired,
    }).isRequired,
  };

  


const CollapsibleTable =  (props) => {
    useEffect(() => {
        props.allOrders();
      }, []);
      let AllOrdersresult = props.allOrdersState.map(item => ({
        order_id: item.order.order_id,
        net_total: item.order.net_total,
        tax_total: item.order.tax_total,
        date_created: item.order.date_created.split(' ')[0],
        shipping_total: item.order.shipping_total,
        product_qty: item.product_qty,
        first_name: item.customer.first_name,
        last_name: item.customer.last_name,
        email: item.customer.email,
    
       })); 
      
      const rows = [
         {
            name:'shafiq',
            calories:'test',
            fat:'test fat',
            carbs:'test carbs',
            protein:'test protein',
            price:2000,
            history: [
              { 'date': '2020-01-05', 'customerId': '11091700', 'amount': 3 },
              { 'date': '2020-01-02', 'customerId': 'Anonymous', 'amount': 1 },
            ],
          },
    
          {
            name:'Mazhar',
            calories:'test',
            fat:'test fat',
            carbs:'test carbs',
            protein:'test protein',
            price:2000,
            history: [
              { 'date': '2020-01-05', 'customerId': '11091700', 'amount': 3 },
              { 'date': '2020-01-02', 'customerId': 'Anonymous', 'amount': 1 },
            ],
          },
    
          {
            name:'Hanan Khan',
            calories:'test',
            fat:'test fat',
            carbs:'test carbs',
            protein:'test protein',
            price:2000,
            history: [
              { 'date': '2020-01-05', 'customerId': '11091700', 'amount': 3 },
              { 'date': '2020-01-02', 'customerId': 'Anonymous', 'amount': 1 },
            ],
          }
    
    
      ];
      
  return (
    <TableContainer component={Paper}>
    <Table aria-label="collapsible table">
      <TableHead>
        <TableRow>
          <TableCell />
          <TableCell>Dessert (100g serving)</TableCell>
          <TableCell align="right">Calories</TableCell>
          <TableCell align="right">Fat&nbsp;(g)</TableCell>
          <TableCell align="right">Carbs&nbsp;(g)</TableCell>
          <TableCell align="right">Protein&nbsp;(g)</TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        {rows.map((row) => (
          <Row key={row.name} row={row} />
        ))}
      </TableBody>
    </Table>
  </TableContainer>
  );
}

const mapStateToProps = state => {
    return {
       allOrdersState:state.homeReducer.allOrders,
    };
  };
  
  const mapDispatchToProps = {
    allOrders:homeActions.allOrders,
    // allStocks:homeActions.allStocks,
    // allUsers:homeActions.allUsers
  
  };
  
  const connectCollapsibleTable = connect(
    mapStateToProps,
    mapDispatchToProps
  )(CollapsibleTable);
  
  export { connectCollapsibleTable as CollapsibleTable };
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

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

1 Ответ

0 голосов
/ 15 июля 2020

Я решил проблему. поскольку я заполняю данные из хранилища redux, поэтому я беру пустой массив, тогда я беру l oop и помещаю объекты внутри массива и показываю соответствующие элементы объекта в соответствующих tableCells.

Пожалуйста, посмотрите на my CollapsibleTable Component и сравните его со складными таблицами MaterialUI, тогда вы лучше поймете, как заполнять динамические c данные в строках таблицы. введите здесь код

import { connect } from "react-redux";
import PropTypes from 'prop-types';
import {homeActions} from '../../store/home/actions'
import { makeStyles } from '@material-ui/core/styles';
import Box from '@material-ui/core/Box';
import Collapse from '@material-ui/core/Collapse';
import IconButton from '@material-ui/core/IconButton';
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 Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import KeyboardArrowDownIcon from '@material-ui/icons/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@material-ui/icons/KeyboardArrowUp';
import Button from '@material-ui/core/Button';

const useRowStyles = makeStyles({
  root: {
    '& > *': {
      borderBottom: 'unset',
    },
  },
});
function Row(props) {
    const { row } = props;
    const [open, setOpen] = React.useState(false);
    const classes = useRowStyles();
  
    return (
      <React.Fragment>
        <TableRow className={classes.root}>
          <TableCell>
            <IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)}>
              {open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
            </IconButton>
          </TableCell>
          <TableCell component="th" scope="row">{row.order_id}</TableCell>
          <TableCell align="right">{row.date_created}</TableCell>
          <TableCell align="right">{row.status}</TableCell>
          <TableCell align="right">{row.total_sales}</TableCell>
          <TableCell align="right">
          <Button variant="contained" color="primary">Order Again </Button>
          </TableCell>
        </TableRow>
        <TableRow>
          <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={6}>
            <Collapse in={open} timeout="auto" unmountOnExit>
              <Box margin={1}>
                <Typography variant="h6" gutterBottom component="div">
                  History
                </Typography>
                <Table size="small" aria-label="purchases">
                  <TableHead>
                    <TableRow>
                      <TableCell>Date</TableCell>
                      <TableCell>Customer</TableCell>
                      <TableCell align="right">Amount</TableCell>
                      <TableCell align="right">Total price ($)</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {row.history.map((historyRow) => (
                      <TableRow key={historyRow.date}>
                        <TableCell component="th" scope="row">
                          {historyRow.date}
                        </TableCell>
                        <TableCell>{historyRow.customerId}</TableCell>
                        <TableCell align="right">{historyRow.amount}</TableCell>
                        <TableCell align="right">
                          {Math.round(historyRow.amount * row.price * 100) / 100}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </Box>
            </Collapse>
          </TableCell>
        </TableRow>
      </React.Fragment>
    );
  }
  
  Row.propTypes = {
    row: PropTypes.shape({
      calories: PropTypes.number.isRequired,
      carbs: PropTypes.number.isRequired,
      fat: PropTypes.number.isRequired,
      history: PropTypes.arrayOf(
        PropTypes.shape({
          amount: PropTypes.number.isRequired,
          customerId: PropTypes.string.isRequired,
          date: PropTypes.string.isRequired,
        }),
      ).isRequired,
      name: PropTypes.string.isRequired,
      price: PropTypes.number.isRequired,
      protein: PropTypes.number.isRequired,
    }).isRequired,
  };

const CollapsibleTable =  (props) => {

    useEffect(() => {
        props.allOrders();
      },[]);
      
    const ordersTest = [];

    for (let i = 0; i < props.allOrdersState.length && props.allOrdersState.length; i++) {
        ordersTest.push({
            order_id: props.allOrdersState.length ? props.allOrdersState[0]['order']['order_id'] :'',
            total_sales: props.allOrdersState.length ? props.allOrdersState[0]['order']['total_sales'] :'',
            status: props.allOrdersState.length ? props.allOrdersState[0]['order']['status'] :'',
            tax_total:props.allOrdersState.length ? props.allOrdersState[0]['order']['tax_total'] :'',
            date_created: props.allOrdersState.length ? props.allOrdersState[0]['order']['date_created'] :'',
            shipping_total: props.allOrdersState.length ? props.allOrdersState[0]['order']['shipping_total'] :'',
            product_qty: props.allOrdersState.length ? props.allOrdersState[0]['product_qty'] :'',
            first_name:  props.allOrdersState.length ? props.allOrdersState[0]['customer']['first_name'] :'',
            last_name:  props.allOrdersState.length ? props.allOrdersState[0]['customer']['last_name'] :'',
            email:  props.allOrdersState.length ? props.allOrdersState[0]['customer']['email'] :'',
            history: [
                { date: '2020-01-05', customerId: '11091700', amount: 3 },
                { date: '2020-01-02', customerId: 'Anonymous', amount: 1 },
              ],
        });
    }
     

      console.log('all orders for each....', ordersTest);
    
      
  return (
    <TableContainer component={Paper}>
    <Table aria-label="collapsible table">
      <TableHead style={{background:'#f4511e'}}>
        <TableRow>
          <TableCell />
          <TableCell>Order No.</TableCell>
          <TableCell align="right">Date</TableCell>
          <TableCell align="right">Status</TableCell>
          <TableCell align="right">Total</TableCell>
          <TableCell align="right">Actions</TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        {ordersTest.slice(0, 10).map((row) => (
          <Row key={row.order_id} row={row} />
        ))}
      </TableBody>
    </Table>
  </TableContainer>
  );
}

const mapStateToProps = state => {
    return {
       allOrdersState:state.homeReducer.allOrders,
    };
  };
  
  const mapDispatchToProps = {
    allOrders:homeActions.allOrders,
    // allStocks:homeActions.allStocks,
    // allUsers:homeActions.allUsers
  
  };
  
  const connectCollapsibleTable = connect(
    mapStateToProps,
    mapDispatchToProps
  )(CollapsibleTable);
  
  export { connectCollapsibleTable as CollapsibleTable };
     ```
...