在我useEffect嘗試獲取用戶 ID 令牌時,當我擁有此令牌時,我會fetch從我的服務器獲取資料,令牌為authorization header. 使用資料填充一些highcharts選項并呈現圖表。
問題是我無法訪問[[PromiseResult]],它回傳完整的Promise.
我firebase用作用戶資料庫并將用戶身份驗證包裝在context.
編輯:我使用的 id 我.then()將不得不重復一堆我的代碼兩次,因為我的header常數取決于結果,而資料的獲取取決于header這樣的:
if(currentUser) {
await currentUser.getIdToken(/* forceRefresh */ true).then(
// ... defining the header with idToken
// ... continue with the rest
)
} else {
// ... defining the header as "unauthorized"
// ... continue with the rest
}
那么它的解決方案是什么?
這是我的完整組件:
import React, {useState, useEffect } from "react";
import Highcharts from "highcharts/highstock";
import HighchartsReact from "highcharts-react-official";
import { useAuth } from "../../../contexts/AuthContext"
import ChartLoadingScreen from '../ChartLoadingScreen'
export default function MyChart(){
const [isMounted, setMounted] = useState(false)
const [options, setOptions] = useState(HighchartsTheme)
const { currentUser } = useAuth();
const HighchartsTheme = {
title: {
text: undefined,
},
series: [ ],
accessibility: {
enabled: false
},
yAxis: [{
opposite: true,
type: 'linear',
labels: {
align:'right',
},
},
{
opposite: false,
type: 'logarithmic',
}]
};
useEffect(() => {
const getIdToken = async () => {
const idToken = await currentUser.getIdToken(/* forceRefresh */ true);
return(idToken);
}
setMounted(false);
console.log(currentUser)
const idToken = currentUser ? getIdToken() : "unauthorized";
console.log(idToken)
let headers = new Headers();
headers.append('authorization', idToken);
Promise.all([
fetch("https://my-server-side/data1"),
fetch("https://my-server-side/data2", { headers: headers })
]).then(responses =>
Promise.all(responses.map(response => response.json()))
).then(data => {
console.log(data);
setSeriesData(data[1]);
options.series = [{ data: data[0], yAxis: 1}];
options.series.push({ data: data[1], yAxis: 0})
updateChart();
setMounted(true);
}
).catch(err =>
console.log(err)
);
return () => {
setMounted(false);
setOptions({});
};
}, [chartDataEndpoint]);
const updateChart = () => {
setOptions(prevState => ({ ...prevState}));
};
return (
<>
{isMounted ?
<>
<div>
<HighchartsReact
highcharts={Highcharts}
constructorType={"stockChart"}
options={options}
/>
</div>
</>
:
<ChartLoadingScreen isDefault={true}/>
}
</>
);
}
uj5u.com熱心網友回復:
它的 dismount 函式的一個問題useEffect是形式 -> () => void,而不是() => Promise<void>,因此如果您只是將 a 標記useEffect為async函式,它將回傳一個 Promise,而 React 只是期待一個函式而不是一個 Promise。
一個簡單的解決方案是將代碼包裝在asnyc IFFE..
例如。
useEffect(() => {
(async () => {
//we can now use async/await.
.....
const idToken = currentUser ? await getIdToken() : "unauthorized";
.....
})();
//our return is still a plain function
return () => {
//dismount stuff here
}
},[chartDataEndpoint]);
uj5u.com熱心網友回復:
您的 useEffect “回呼”應該是異步的:
useEffect(async() => {
let x = await fetch(URL);
x = await x.json();
setData(x);}, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/527658.html
標籤:Google Cloud Collective javascript反应火力基地反应钩子异步等待
