0

我想将道具从我的父组件发送到子组件。这是我在父组件状态中使用的方式-->

chartArray:[
        {
            id:0,
            chart:'LineChart',
            device:1,
            sensor:1,

        },
        {
            id:1,
            chart:'LineChart',
            device:2,
            sensor:4,
        },]

在父组件渲染方法中->我使用图表组件并发送这些道具

                            {
                            chartArray.map((obj,index)=>{

                                return(
                                    <Grid item xs={12} md={12} key={index}
                                    className={classes.mainGrid} 
                                    style={{paddingBottom:30}}
                                     >


                                    <div>
                                        <div  >
                                            <div>
                                            <Typography
                                            variant={"h5"}
                                            >
                                                Device Id: {obj.device}

                                                <IconButton style={{float:'right'}}
                                                onClick={this.handleDeleteChart.bind(this,index)}
                                                >
                                                    <DeleteIcon fontSize="small" />
                                                </IconButton>
                                            </Typography>
                                            </div>

                                        </div>

                                        <div>
                                        <Typography variant={"subtitle1"}>
                                            Sensor: Temperature
                                        </Typography>

                                        </div>
                                    </div>


                                        <Paper elevation={3} 
                                        style={{
                                            overflowX: 'scroll',

                                        }}
                                        >
                                            **<Chart
                                            chartType={obj.chart} 
                                            sensorId={obj.sensor}
                                            deviceId={obj.device}
                                            />**

                                        </Paper>
                                    </Grid>

                                )



                            }

                        )}

在子组件中-->

导出默认类图表扩展组件{

constructor(props){
    super(props);

    this.state={
        id:0,
        chart:props.chartType,
        device:props.deviceId,
        sensor:props.sensorId,
    }
}

async componentDidMount(){

    const response2 = await fetch(`/api/SensorData/${this.state.device}/${this.state.sensor}`)
    const bodySensors = await response2.json()

    const labels1=[]
    const data1=[]

    bodySensors.map((chartdata)=>{
        return(
            labels1.push(chartdata.date),
            data1.push(chartdata.value)
        )

    })

    this.setState({

        dataLineChart:{
            labels:[...labels1],
            datasets:[
                {
                fill:false,
                label:'Temperature',
                data:[...data1],
                backgroundColor:'rgba(210, 77, 87, 1)',
                borderColor:'rgba(137, 196, 244, 1)',
                pointBorderWidth:1,
                pointHoverRadius:10,
                pointHoverBackgroundColor:'rgba(210, 77, 87, 1)',
                pointHoverBorderColor:'rgba(137, 196, 244, 1)',
                pointHoverBorderWidth:2,
                pointRadius:2,
                // how much closer to pop up point
                pointHitRadius:10

                // steppedLine:true
            }
        ]

        }

    })


}



render() { 
    const{chartType}=this.props
    const {dataLineChart} = this.state        

    if (chartType==='BarChart')
        return (
            <BarChart />
        )
    else if (chartType==='LineChart')
        return (
            <LineChart ccData={dataLineChart}/>
        )
    else if (chartType==='PieChart')
        return (
            <PieChart/>
        )
}

}

当我使用这种方式在渲染功能之外使用这些道具时。有用。当我将对象添加到父组件状态时-> chartArray 它也可以工作。但是,当我从该 chartArray 中删除某些内容时,它不会向子组件发送道具吗?我在这里真的很困惑。请帮忙。谢谢

4

2 回答 2

0

因为每次父道具更改时不会重新渲染子对象,所以您需要更改的是子组件而不是componentDidMount使用componentDidUpdate。在其中,您必须使用简单的 if 语句检查传递的 props 值。某种意义上的东西:

    componentDidUpdate(prevProps) {
    if(prevProps.chartType !== this.props.chartType||prevProps.sensorId !== 
    this.props.sensorId||prevProps.deviceId !== this.props.deviceId) { ...... your code}

}

当然,这是假设其他一切工作顺利。

于 2020-04-18T13:36:08.830 回答
0

请按照这个例子。

父组件

import React, {Component, useEffect, useState} from 'react';
import PChild from "./PChild";

export class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {items: []};
    }

    componentDidMount() {
        let json = [];
        json.push({track: { id:1, name: 'Black Sabbath, from the album Black Sabbath (1970)'}});
        json.push({track: { id:2, name: 'Blackfield, from the album Blackfield (2004)'}});
        json.push({track: { id:3, name: 'Bo Diddley, from the album Bo Diddley (1958)'}});
        json.push({track: { id:4, name: 'Damn Yankees, from the album Damn Yankees (1990)'}});
        this.setState({items: json});
    }

    render() {
        return (
            <div>
                <PChild items={this.state.items} name="Khabir"/>
            </div>
        );
    }
}

子组件

import React, {useEffect, useState} from 'react';

// Parent to Child communication
export class PChild extends React.Component {

    componentDidUpdate() {
        console.log(this.props.items);
        console.log(this.props.name);
    }

    render() {
        return (
            <div>
                {this.props.items.map((item, i) => {
                    return <li key={item.track.id}>
                        {(`Item ${i+1} - ${item.track.name}`)}
                    </li>
                })}
            </div>
        );
    }
}
于 2020-04-16T17:18:03.563 回答