首页 > 解决方案 > 从 useEfect 发送 Prop

问题描述

应用程序.js ->

<Lobbies inGame={inGame} setLobby={setLobby} userName={userName} userKey={userKey}/>

Lobbies.js ->

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

const Lobby = ({userKey, userName}) => {

    useEffect(() => {
        if (lobbyCreated){
            const db = firebase.database().ref(`Lobby/${lobbyKey}/players`);

            const listener = db.on('value', snapshot => {
                var fetchedTasks = [];

                fetchedTasks = snapshot.val();

                console.log(fetchedTasks[0]['game']);

                if (fetchedTasks[0]['game']) {
                    //SEND PROP BACK TO APP.JS BELOW
                    props.inGame(true, lobbyKey);
                }else{
                    if (fetchedTasks.length != players.length)  setPlayers(fetchedTasks);
                }
            });

            return () => db.off('value', listener);
        }
    });
};

如何使用 useEffect 从 Lobbies.js 将道具发送回 App.js?(有评论想把道具寄回去)谢谢

标签: javascriptreactjsreact-native

解决方案


你已经大部分时间在那里,你只需要setLobby在你的useEffect钩子中调用你的回调。

回调已经被 传递App,只需从您的道具中解构它(与任何其他道具相同)并使用lobbyKey(或您想要“发回”的任何其他内容)调用它。


推荐阅读