我希望React只在一个值被给定给一个变量后返回一个代码。
这段代码启动了我的聊天室:
<section>
{user ? <ChatRoom/> : <SignIn />}
</section>
在我的函数中,我有这段代码。我正在尝试从Firestore获取信息。
firestore.collection("mailpairing").doc(auth.currentUser.email).get().then((d) => {
othermail=d.data().mail;
console.log("test123",auth.currentUser.email," + ",othermail);
firestore.collection("tokens").doc(othermail).get().then((da)=> {
othertoken=da.data().token;
console.log("másik token: " + othertoken);
});
});
在最后我有这样的返回语句:
if(othertoken!=null){
console.log("token???");
return(
<>
<BrowserRouter>
<Route exact path="/" render={() => {window.location.href="tv/indexTv.html?m="+auth.currentUser.email+"&p="+othermail+"&t="+othertoken}} />
</BrowserRouter>
</>
)}
else{
return null;
}
如果我像这样保留代码,就不会返回任何东西。如果我删除If语句,则返回我想要的站点,但是我想传递给URL的令牌是未定义的。我该如何解决这个问题?由于某些原因,我不能使函数异步,从另一个函数请求数据不起作用。
编辑:解决了!我添加了一个UseState.
const [HaveToken, setTokenValue] = useState(false);
我从Firestore获得数据后将其更改为true,并在返回中添加了一些内容:
{HaveToken ? (
<BrowserRouter>
<Route exact path="/" render={() => {window.location.href="tv/intv.html?m="+auth.currentUser.email+"&p="+othermail+"&t="+othertoken}} />
</BrowserRouter>
):null}
现在运行良好。
您可以使用async/await
以这种方式获得令牌,您只需要将return
替换为resolve function
,然后就可以了。
const othertoken = await Promise((resolve, reject) => {
firestore
.collection('mailpairing')
.doc(auth.currentUser.email)
.get()
.then(d => {
othermail = d.data().mail;
console.log('test123', auth.currentUser.email, ' + ', othermail);
firestore
.collection('tokens')
.doc(othermail)
.get()
.then(da => {
othertoken = da.data().token;
console.log(`másik token: ${othertoken}`);
resolve(othertoken);
});
});
});
以更好的方式
const othertoken = await Promise(async (resolve, reject) => {
const d = await firestore.collection('mailpairing').doc(auth.currentUser.email).get();
const othermail = d.data().mail;
console.log('test123', auth.currentUser.email, ' + ', othermail);
const da = await firestore.collection('tokens').doc(othermail).get();
const othertoken = da.data().token;
console.log(`másik token: ${othertoken}`);
resolve(othertoken);
});
没有返回任何东西的原因是因为您对firestore的调用是异步的。也就是说,当执行实际到达if语句时,您所做的调用还没有完成,因此othertoken
还没有接收到值。正如我所看到的,您可以通过使用async
关键字将方法标记为异步方法,并使用await
,或者您可以将回调传递给接受令牌的函数。使用等待:
const doc = await firestore.collection("mailpairing").doc(auth.currentUser.email).get();
const mail = doc.data().mail;
const token = await firestore.collection("tokens").doc(othermail).get();
const othertoken= da.data().token;
if(othertoken!=null){
return (
<>
<BrowserRouter>
<Route exact path="/" render={() =>
{window.location.href="tv/indexTv.html?m="+auth.currentUser.email+"&p="+othermail+"&t="+othertoken}} />
</BrowserRouter>
</>
)}
else {
return null;
}
如果使用回调,那么您将声明一个接受令牌作为参数的方法:
const myCallback = token => {
// do something with the token
}
并将othertoken=da.data().token;
行更改为myCallback(da.data().token)
,并将myCallback
作为参数传递给函数。