首页 > 解决方案 > 我想了解为什么我作为道具传递给 React 功能组件的数据显示为未定义?

问题描述

我得到了一个现成的反应组件,我需要在其中将数据作为道具传递,但不知何故,当我控制台记录它时,我无法看到道具数据。有人可以帮助我了解我是否正确传递了道具。我不知道这里使用的是什么类型的功能组件以及我传递的道具是否正确输入。我将相同的道具传递给其他基于类的组件,这些组件确实正确显示了数据。

    import React from 'react';  
    import { withStyles } from '@material-ui/core/styles';  
    import Button from '@material-ui/core/Button';
    import Dialog from '@material-ui/core/Dialog';
    import MuiDialogTitle from '@material-ui/core/DialogTitle';
    import MuiDialogContent from '@material-ui/core/DialogContent';
    import MuiDialogActions from '@material-ui/core/DialogActions';
    import IconButton from '@material-ui/core/IconButton';
    import CloseIcon from '@material-ui/icons/Close';
    import Typography from '@material-ui/core/Typography';
    
    
    const styles = (theme) => ({
        root: {
            margin: 0,
            padding: theme.spacing(2),
        },
        closeButton: {
            position: 'absolute',
            right: theme.spacing(1),
            top: theme.spacing(1),
            color: theme.palette.grey[500],
        },
    });
    
    const DialogTitle = withStyles(styles)((props) => {
        
        const { children, classes, onClose, routeHappyData, ...other } = props;
        console.log(routeHappyData);
        return (
            <MuiDialogTitle disableTypography className={classes.root} {...other}>
                <Typography variant="h6">{children}</Typography>
                {onClose ? (
                    <IconButton aria-label="close" className={classes.closeButton} onClick={onClose}>
                        <CloseIcon />
                    </IconButton>
                ) : null}
            </MuiDialogTitle>
        );
    });  

``


```The prop I want to pass is "routeHappyData" which is showing undefined when console logged.
In the Parent class component i am passing the prop this way given below```

        render() {
            let {      
              routeHappyData
              
                } = { ...this.props };
            return (
    
         <div>{noOfStops}</div>
                                {<CovidHealthSafety routeHappyData={this.props.routeHappyData}/>}
                    </div>
    )

标签: javascriptarraysreactjsmaterial-ui

解决方案


在分配变量console.log之前,您可以使用它。routeHappyData试着把它放在下面一行。

const DialogTitle = withStyles(styles)((props) => {
    const { children, classes, onClose, routeHappyData, ...other } = props;
    console.log(routeHappyData);
    return (
        <MuiDialogTitle disableTypography className={classes.root} {...other}>
            <Typography variant="h6">{children}</Typography>
            {onClose ? (
                <IconButton aria-label="close" className={classes.closeButton} onClick={onClose}>
                    <CloseIcon />
                </IconButton>
            ) : null}
        </MuiDialogTitle>
    );
});  

推荐阅读