javascript - 从 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?(有评论想把道具寄回去)谢谢
解决方案
你已经大部分时间在那里,你只需要setLobby
在你的useEffect
钩子中调用你的回调。
回调已经被 传递App
,只需从您的道具中解构它(与任何其他道具相同)并使用lobbyKey
(或您想要“发回”的任何其他内容)调用它。
推荐阅读
- java - 使用 SWIG 在 Java 和 C++ 之间传递缓冲区
- java - 使用归纳法证明此递归算法的正确性
- javascript - Node.js + Express 不使用 FS 写入文件
- macos - 端口 80 在 macbook localhost 上不可用
- python - 输出不会输出到标准输出
- python - How can i implement Vector addition for the form [1,2,3,4] + v where v is vector and [1,2,3,4] is a list in python?
- javascript - Javascript TypeError:var不是函数
- spring - java.lang.AbstractMethodError in spring data Cassandra 1.5.x version with spring framework 4.3.x version
- flutter - 在 Flutter 中的 Scroll 上隐藏底部导航栏
- php - sudo apt-get install php5-xsl 给出 403 Forbidden 错误