首页 > 解决方案 > Wordpress Gutenberg Block - ReactJS - 从 Firebase.Firestore 获取第三方数据

问题描述

我正在尝试编写一个 Gutenberg Block 来从 Googles Firestore 加载一些数据。

这是我的第一个 ReactJS 项目,因为我认为这应该很容易:D 后端很好,并设置了所有需要的属性。我想我在这里只错过了一件小事,但这已经困扰了我好几天了。

我被困的地方是const getData = () => {...getDoc(...)。似乎Promise<DocSnap>永远得不到解决

    import { initializeApp } from 'firebase/app';
    import { getFirestore, doc, getDoc } from 'firebase/firestore';

    const { render } = wp.element;

    let state = '';
    let data = '';

    if ( typeof window.firebaseOptions !== 'undefined' ) {
        // Initialize FirebaseApp
        const firebaseApp = initializeApp( window.firebaseOptions );
        state = 'initialized';
        const db = getFirestore();
        const docRef = doc( db, 'myDoc', window.docId );

        const appendData = ( result ) => {
            const text = document.createTextNode(
                window.docId+ ': ' + result
            );
            data = text;
            state = 'texted';
        };

        const getData = () => {
            state = 'loading';
            getDoc( docRef ).then( ( data ) => {
                state = 'promised';
                let result = '';
                if ( doc.exists ) {
                    result = JSON.stringify( doc.data(), undefined, 2 );
                } else {
                    result =
                    'No Doc with ID ' + window.docId + ' found.';
                }
                appendData( result );
            } );
        };
        getData();
    } else {
        //TODO Warning message
    }

    const Block = ( { element } ) => (
        <div >
            <div element={ element } >Doc: { window.docId }</div>
            <div element={ element } >state: { state }</div>
            <pre>{ data }</pre>
        </div>
    );

    window.addEventListener( 'DOMContentLoaded', () => {
        const blocks = document.querySelectorAll( '.wp-block-my-wp-block' );
        blocks.forEach( ( block ) => {
            render(
                <Block element={ block } />,
                block
            );
        } );
    } );

这是输出: 在此处输入图像描述

标签: reactjswordpressfirebasewordpress-gutenberg

解决方案


推荐阅读