Ionic 从父类传递时未定义属性

vzgqcmou  于 2022-12-16  发布在  Ionic
关注(0)|答案(1)|浏览(159)

(免责声明-我是一个noob)我遇到了一个问题,而试图实现电容器设备API到我的离子React项目。 prop (mobileInfo)正在传递到我的DeviceView函数是未定义的。谁能解释这是为什么?

设备容器.tsx**

import {Component} from "react";
import DeviceView from './DeviceView';
import React, { useEffect, useState } from 'react';
import { Device } from '@capacitor/device';

export class DeviceContainer extends React.Component {

    
    state: { mobileInfo: string }
    

    constructor(props: any) {
        super(props)

        this.state =
        {
            mobileInfo: "",

        }
    }
    async getDeviceInfo (){

        const info =  Device.getInfo();

        this.setState({

            mobileInfo: JSON.stringify(info)
            

        });
    }

    componentDidMount() {
        this.getDeviceInfo();
    }

    render() {

        return (
            
            <DeviceView
                mobileInfo={this.state.mobileInfo}
            />

        )
    }
}
export default DeviceContainer;

设备视图.tsx**

import React from 'react'
import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar } from '@ionic/react';
import DeviceContainer from './DeviceContainer'
import { RouteComponentProps } from 'react-router';

const DeviceView = ({ mobileInfo }: any) => {

    if (mobileInfo !== undefined) {
        console.log('prop was passed');
      } else {
        console.log('prop was NOT passed');
      }

    return (
        <IonPage>
            <IonHeader>
                <IonToolbar>
                    <IonTitle>Device Info</IonTitle>
                </IonToolbar>
            </IonHeader>
            <IonContent fullscreen>
                <div>
                    <div>
                        Mobile Info: {mobileInfo}
                    </div>
                </div>
            </IonContent>
        </IonPage>
    )
}

export default DeviceView;

我希望DeviceView.tsx使用mobileInfo属性显示用户的设备信息。

disho6za

disho6za1#

尝试awaitDevice.getInfo(),因为此方法是异步的。

async getDeviceInfo(){

    const info = await Device.getInfo();
    console.log('---info', info)
    this.setState({
        mobileInfo: JSON.stringify(info)
    });
}

async componentDidMount() {
    await this.getDeviceInfo();
}

相关问题