【问题标题】:How to display state object elements in another component?如何在另一个组件中显示状态对象元素?
【发布时间】:2020-06-22 18:14:33
【问题描述】:

我正在尝试使用 MaterialUI 中的表格并使用财务数据填充它(使用 promise API)。我有三个组件:
Gl.js
myTable
index.js

我想使用 Gl.js 组件中的状态对象并在 myTable.js 中填充表格,但不知道如何。如有需要请询问详情,我必须完成这个项目。

GL.js

import React, { Component, createContext, Provider } from 'react';
    import ReactDOM from 'react-dom';
    import axios from "axios";
    import CollapsibleTable from './myTable';

export const CTX = React.createContext();

class Gl extends React.Component {
    _isMounted = false;
    constructor(props) {
        super(props)
        this.state = {
            applBs: []
        }
        
    }

    getData() {

        const axios = require("axios");

        axios({
            "method": "GET",
            "url": "https://fmpcloud.p.rapidapi.com/balance-sheet-statement/AAPL",
            "headers": {
                "content-type": "application/octet-stream",
                "x-rapidapi-host": "fmpcloud.p.rapidapi.com",
                "x-rapidapi-key": "4560d76562msh36c4de0a03c6e54p1bf4a2jsne2d882693304",
                "useQueryString": true
            }, "params": {
                "period": "annual",
                "apikey": "demo"
            }
        })
            .then(response => {
                if (this._isMounted) {
                    this.setState({ applBs: response.data[0] })
                }
            })
    
    
            .catch(error => {
                console.log(error)
            })

    }
    
    componentDidMount() {
        this._isMounted = true;
        this.getData();
    }

    componentWillUnamount() {
        this._isMounted = false;
    }


    render() {
        return (
            <div>
                <CollapsibleTable callData={this.state.applBs} />

            <CTX.Provider value={ this.state.applBs }> 
                {this.props.children}
                </CTX.Provider>

                </div>
        )
    }
}




ReactDOM.render(<Gl />, document.getElementById("root"))

export default Gl

myTable.js

import React, { Component, Consumer } from 'react';
import ReactDOM from "react-dom"
import PropTypes from 'prop-types';
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 CTX from "./GL.js"


const useRowStyles = makeStyles({
    root: {
        '& > *': {
            borderBottom: 'unset',
        },
    },
});

function createData(name, calories, fat, carbs, protein, price) {
    return {
        name,
        calories,
        fat,
        carbs,
        protein,
        price,
        history: [
            { lineItem: 'Pop', date: '2020-01-05', customerId: '11091700', amount: 3 },
            { lineItem: 'Pop', 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>
                                           Line Item
                                            </TableCell>
                                        <TableCell>
                                            Google
                                        </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 rows = [
    createData('Frozen yoghurt', 159, 6.0, 24, 4.0, 3.99),
    createData('Ice cream sandwich', 237, 9.0, 37, 4.3, 4.99),
    createData('Eclair', 262, 16.0, 24, 6.0, 3.79),
    createData('Cupcake', 305, 3.7, 67, 4.3, 2.5),
    createData('Gingerbread', 356, 16.0, 49, 3.9, 1.5),
];

export default function CollapsibleTable() {
    return (
        <TableContainer component={Paper}>
            <Table aria-label="collapsible table">
                <TableHead>
                    <TableRow>
                        <TableCell />
                        <TableCell>
                            Apple.Inc
                        </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>
    );
}

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Gl from './GL';
import CollapsibleTable from './myTable';


ReactDOM.render(
    <React.StrictMode>
        <Gl >
            <CollapsibleTable />
            </Gl>

  </React.StrictMode>,
  document.getElementById('root'));

【问题讨论】:

  • 您以 callData={this.state.applBs} 的名义发送值,但在 myTable.js 中我没有看到您在使用 callData
  • 我尝试使用 {this.props.callData} 但我收到一条错误消息,提示无法读取未定义的属性 'props'。

标签: reactjs react-context


【解决方案1】:

好的,那么这一定是类和功能组件的问题,this关键字只能在类组件中使用!!

查看此链接以获取更多参考link

在你的情况下有一个控制台

<TableContainer component={Paper}>
  {console.log('callData', props.callData)}
 <Table aria-label="collapsible table">

你会得到callData的值,用它来显示在表格中

【讨论】:

  • 我试过这样做,但它说编译失败'callData'没有定义。
  • 你用过props.callData
  • 是的,它说“道具”没有定义
  • export default function(props) 添加此功能组件接收默认参数“props”如果有帮助,请接受并投票赞成答案
  • 不知道老实说我能联系到你吗?
猜你喜欢
  • 1970-01-01
  • 2020-05-02
  • 1970-01-01
  • 2021-10-30
  • 2022-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多