开发者问题收集

TypeError:无法读取未定义的属性“country”-React-Redux

2020-09-10
310

我有一个对象 (tripData) 作为数组 (currentProjectData) 的第一个值 (索引 0),但我无法访问该对象的键值对的值 (例如 country 的值),我收到 TypeError:无法读取未定义的属性“country”。我使用点 (.) 符号来访问键值对。这是在 React 和 Redux 项目中。

在分隔线后的以下大代码块中,您可以专注于 tripData 对象和 getFunc 的调用:

const tripData = {
       //the code you'll see in the following code block
}

getFunc().then((dataOfTripCard) => {
        this.props.currentProjectData([
            dataOfTripCard
        ])
    });

const getFunc = async () => {

        const create_UUID = () => {
            var dt = new Date().getTime();
            var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = (dt + Math.random() * 16) % 16 | 0;
                dt = Math.floor(dt / 16);
                return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
            });
            return uuid;
        }

        const username = process.env.API_USERNAME;
        const weatherbitAPIKey = process.env.weatherbit_API_KEY;
        const pixabayAPIKey = process.env.pixabay_API_KEY;

        const baseURLGeo = "http://api.geonames.org/searchJSON?q=";
        const baseURLWeatherCurrent = "https://api.weatherbit.io/v2.0/current?";
        const baseURLWeatherForecast = "https://api.weatherbit.io/v2.0/forecast/daily?";
        const baseURLPixabay = "https://pixabay.com/api/?";

        const city = this.refs.city.value;
        const depDateFromUser = this.refs.departureDate.value;
        const returnDateFromUser = this.refs.returnDate.value;

        // Create a new date instance dynamically with JS
        const d = new Date();
        const newDate = d.getMonth() + 1 + '/' + d.getDate() + '/' + d.getFullYear();

        const resGeo = await fetch(baseURLGeo + encodeURI(city) + "&username=" + username);

        try {
            const data = await resGeo.json();
            const countryName = data.geonames[0].countryName;
            const latitude = data.geonames[0].lat;
            const longitude = data.geonames[0].lng;
            const daysLeft = timeDiff(newDate, depDateFromUser, returnDateFromUser);

            const resWeather = await fetch(
                ((daysLeft > 7) ? baseURLWeatherForecast : baseURLWeatherCurrent) + "key=" + weatherbitAPIKey + "&lat=" + latitude + "&lon=" + longitude
            );

            const data2 = await resWeather.json();
            const weather = data2.data[0].weather.description;

            const resPixabayPhoto = await fetch(baseURLPixabay + "key=" + pixabayAPIKey + "&q=" + encodeURI(city) + "+tourism&image_type=photo");

            const data3 = await resPixabayPhoto.json();
            const cityPhoto = data3.hits[0].webformatURL;

            // id generated by create_UUID function
            const currentId = create_UUID();

            const tripData = {
                cityPhoto: cityPhoto,
                country: countryName,
                date: newDate,
                depDate: depDateFromUser,
                retDate: returnDateFromUser,
                daysLeft: daysLeft,
                weather: weather,
                temp: (daysLeft > 7) ? {
                    low_temp: data2.data[0].low_temp,
                    max_temp: data2.data[0].max_temp,
                    trueOrFalse: true //For the if statement in updateUI in the client side
                } : {
                        temp: data2.data[0].temp,
                        trueOrFalse: false //For the if statement in updateUI in the client side
                    },
                lat: latitude,
                lng: longitude,
                tripId: currentId
            };

            let dataOfTripCard = [tripData];

            return dataOfTripCard;

        } catch (error) {
            console.log("error", error);
            //appropriately handle the error
        }
    
    };

    getFunc().then((dataOfTripCard) => {
        this.props.currentProjectData([
            dataOfTripCard
        ])
    });

以及渲染和返回内部:

render() { 
    return (
        <div>
            {this.props.submittedOrNot ?
                <div className="title centerTitle">My Trips</div>
                :
                null
            }
            <div id="allEntryHolders">
                {
                    (this.props.currentProjectData[0].country) ?
                        // (this.props.currentProjectData.dataOfTripCard).map((tripDataItem, index) => (
                        //     // <TripCard key={index} id={tripDataItem.id} tripData={tripDataItem} />,
                        //     <p>{tripDataItem + ""}</p>
                        // ))
                        <p> {this.props.currentProjectData[0].country + ""}</p>
                        : null
                }
            </div>
        </div>
    )
}

const mapStateToProps = state => ({
    currentProjectData: state.inputs.currentProjectData,
    submittedOrNot: state.popUp.submittedOrNot
});

const mapDispatchToProps = dispatch => ({
    currentInputs: inputs => dispatch(currentInputs(inputs)),
    toggleSubmittedOrNot: popUp => dispatch(toggleSubmittedOrNot(popUp)),
    currentProjectData: projectData => dispatch(currentProjectData(projectData))
})

export default connect(mapStateToProps, mapDispatchToProps)(BodyOfApp);

这是当我在条件中使用 this.props.currentProjectData.dataOfTripCard 而不是 this.props.currentProjectData[0].country 时 Redux 记录器对 CURRENT_PROJECT_DATA 状态显示的图像,如下所示:

(this.props.currentProjectData.dataOfTripCard) ?
<p> {this.props.currentProjectData[0].country + ""}</p>
: null

这是 Redux 记录器的图像

2个回答

您是否将其作为 props 传递?将其放入 console.log() 中时,您能看到它是什么样子吗?

ttannerma
2020-09-10

我已经弄清楚了问题出在哪里,我将 dataOfTripCard 数组放在这里:

let dataOfTripCard = [tripData];

放在这里的另一个数组里:

getFunc().then((dataOfTripCard) => {
        this.props.currentProjectData([
            dataOfTripCard
        ])
    });

并尝试在这里访问它:

<p> {this.props.currentProjectData[0].country + ""}</p>

我访问它的时候就好像它只是一个数组,而不是数组内的数组,为了解决这个问题,我将代码更改为以下内容:

从这个:

let dataOfTripCard = [tripData];
return dataOfTripCard;

到这个:

return tripData

从这个:

getFunc().then((dataOfTripCard) => {
    this.props.currentProjectData([
        dataOfTripCard
    ])
});

到这个:

getFunc().then((tripData) => {
            this.props.currentProjectData_Action([
                tripData
            ])
        });
Salah Ayman
2020-09-25