如何将数据从一个组件传递到另一个组件?

问题描述 投票:0回答:1

我试图通过 props (props.data) 将

this.state.airQualityData
从 AirPollutionApi 类传递到 Home 类。我该怎么做?

这是我的代码:

AirPollutionApi 类:

import { Component } from 'react';
import Home from '../Home';


var API_KEY = process.env.REACT_APP_OPEN_WEATHER_MAP_API_KEY

class AirPollutionApi extends Component {

    //API preparation, state management, and location management
    state = {
        airQualityData: {},
        latitude: undefined,
        longitude: undefined
    }

    async componentDidMount() {
        await this.retrieveLocation()
        await this.fetchAirQualityData()
    }

    fetchAirQualityData = () => {
        return fetch(
            `http://api.openweathermap.org/data/2.5/air_pollution?lat=${this.state.latitude}&lon=${this.state.longitude}&appid=${API_KEY}`
        )
        .then(res => res.json())
        .then(data => {
            this.setState({
                airQualityData: data
            })
        })
    }

    retrieveLocation = () => {
        return new Promise((resolve, reject) => {
            navigator.geolocation.getCurrentPosition((position) => {
                // eslint-disable-next-line
                this.state.latitude = position.coords.latitude
                // eslint-disable-next-line
                this.state.longitude = position.coords.longitude
                resolve();
            })
        })
    }


    // Getting all data from API 
    getAQIValue = () => {
        if(this.state.airQualityData.list){
            return this.state.airQualityData.list["0"].main.aqi * 100
        } else {
            return undefined
        }
    }

    getCOValue = () => {
        if(this.state.airQualityData.list){
            return this.state.airQualityData.list["0"].components.co
        } else {
            return undefined
        }
    }

    getNH3Value = () => {
        if(this.state.airQualityData.list){
            return this.state.airQualityData.list["0"].components.nh3
        } else {
            return undefined
        }
    }

    getNOValue = () => {
        if(this.state.airQualityData.list){
            return this.state.airQualityData.list["0"].components.no
        } else {
            return undefined
        }
    }

    getO3Value = () => {
        if(this.state.airQualityData.list){
            return this.state.airQualityData.list["0"].components.o3
        } else {
            return undefined
        }
    }

    getPM2_5Value = () => {
        if(this.state.airQualityData.list){
            return this.state.airQualityData.list["0"].components.pm2_5
        } else {
            return undefined
        }
    }

    getPM10Value = () => {
        if(this.state.airQualityData.list){
            return this.state.airQualityData.list["0"].components.pm10
        } else {
            return undefined
        }
    }

    getSO2Value = () => {
        if(this.state.airQualityData.list){
            return this.state.airQualityData.list["0"].components.so2
        } else {
            return undefined
        }
    }


    render() {
        console.log(this.state.airQualityData)

        return (
            
            
            <div>

                {/* TRYING TO PASS THE 'this.state.airQualityData' HERE */}
                {/* AQI */}
                {this.props.data.includes("aqi") || this.props.data.includes("AQI")  ? 
                
                    <div style={this.props.aqiStyle} className='aqi-value'>
                        {this.getAQIValue()}
                    </div>
                : null}
                
                {/* CO */}
                {this.props.data.includes("co") || this.props.data.includes("CO")  ? 
                
                    <div style={this.props.coStyle} className='co-value'>
                        {this.getCOValue()}
                    </div>
                : null}

                {/* NH3 */}
                {this.props.data.includes("nh3") || this.props.data.includes("NH3")  ? 
                
                    <div style={this.props.nh3Style} className='nh3-value'>
                        {this.getNH3Value()}
                    </div>
                : null}

                {/* NO */}
                {this.props.data.includes("no") || this.props.data.includes("NO")  ? 
                
                    <div style={this.props.noStyle} className='no-value'>
                        {this.getNOValue()}
                    </div>
                : null}
                
            </div>
        )
    }
}

export default AirPollutionApi;

Home 类(尝试通过“props.data”将数据传递给组件):

import React from 'react';
import ReactSpeedometer from 'react-d3-speedometer';

import AirPollutionApi from './utils/airPollutionApi'

const Home = (props) => {


    return (
        
        <div>
            <h1 style={{fontFamily: "Montserrat", textAlign: "center", fontSize: "300%"}}>
                AQI:
            </h1>
            <ReactSpeedometer value={props.data} maxValue={500} minValue={0} />
            <AirPollutionApi data=""/>
        </div>
    );
};

export default Home;

我尝试将组件放入 AirPollutionApi 的返回中,如下所示:

return (
            
            
            <div>

                <Home data={this.state.airQualityData}/>

                {/* AQI */}
                {this.props.data.includes("aqi") || this.props.data.includes("AQI")  ? 
                
                    <div style={this.props.aqiStyle} className='aqi-value'>
                        {this.getAQIValue()}
                    </div>
                : null}
                
                {/* CO */}
                {this.props.data.includes("co") || this.props.data.includes("CO")  ? 
                
                    <div style={this.props.coStyle} className='co-value'>
                        {this.getCOValue()}
                    </div>
                : null}

                {/* NH3 */}
                {this.props.data.includes("nh3") || this.props.data.includes("NH3")  ? 
                
                    <div style={this.props.nh3Style} className='nh3-value'>
                        {this.getNH3Value()}
                    </div>
                : null}

                {/* NO */}
                {this.props.data.includes("no") || this.props.data.includes("NO")  ? 
                
                    <div style={this.props.noStyle} className='no-value'>
                        {this.getNOValue()}
                    </div>
                : null}
                
            </div>
        )

但它只会使本地主机崩溃。

reactjs react-hooks state
1个回答
0
投票

空气中污染Api类:

import React, { Component } from 'react';

var API_KEY = process.env.REACT_APP_OPEN_WEATHER_MAP_API_KEY

class AirPollutionApi extends Component {
    // ...your existing code

    render() {
        return (
            <div>
                <Home data={this.state.airQualityData} />
            </div>
        )
    }
}

export default AirPollutionApi;

和在家:

import React from 'react';
import ReactSpeedometer from 'react-d3-speedometer';

const Home = (props) => {
    const airQualityData = props.data; // data received from props

    // ...rest of the code

    return (
        <div>
            <h1 style={{ fontFamily: "Montserrat", textAlign: "center", fontSize: "300%" }}>
                AQI:
            </h1>
           
            <ReactSpeedometer value={getAQIValue(airQualityData)} maxValue={500} minValue={0} />
          
        </div>
    );
};

// Function to get AQI value from airQualityData
const getAQIValue = (data) => {
    if (data && data.list) {
        return data.list[0].main.aqi * 100;
    } else {
        return undefined;
    }
};

export default Home;
© www.soinside.com 2019 - 2024. All rights reserved.