如何在JavaScript中访问函数内部的变量



我即将完成React Native的第一个项目,这是一个支出应用程序。

我正在用两种货币从我的所有支出中构建一个图表,代码正在运行,我只是在访问本地变量时遇到了一个小问题。

我想访问这个函数中的2sum变量,这样我就可以在React Native的返回中使用它来构建图表。

// Get $ currency From fire base
const q = query(collection(db, "users"),where("selected", "==", "Gasto"), where("moneda", "==", "$"));
const unsubscribe = onSnapshot(q,(querySnapshot) => {
const dolarCurrency = [];
const months =[];
querySnapshot.forEach((doc) =>{
dolarCurrency.push(doc.data().cantidad);
months.push(doc.data().fecha)
})
const hash = months.map((Day) => ({ Day }));
const hashDolar = dolarCurrency.map(( Amount ) => ({ Amount }))
const output = hash.map(({Day},i) => ({Day, ...hashDolar[i]}));

/// I need this variable below
const sum = output.reduce((acc, cur)=> {
const found = acc.find(val => val.Day === cur.Day)
if(found){
found.Amount+=Number(cur.Amount)
}
else{
acc.push({...cur, Amount: Number(cur.Amount)})
}
return acc
}, [])
})
// Get C$ currency from Firebase
const q2 = query(collection(db, "users"), where("selected", "==", "Gasto"),where("moneda", "==", "C$"));
const unsubscribe2 = onSnapshot(q2, (querySnapshot) =>{
const localCurrency = [];
const months2 = [];
querySnapshot.forEach((doc) => {
localCurrency.push(doc.data().cantidad)
months2.push(doc.data().fecha)
})
const hash = months2.map((Day) => ({ Day }));
const hashLocalCurrency = localCurrency.map(( Amount ) => ({ Amount }))
const output = hash.map(({Day},i) => ({Day, ...hashLocalCurrency[i]}));
/// I need this variable below
const sum = output.reduce((acc, cur)=> {
const found = acc.find(val => val.Day === cur.Day)
if(found){
found.Amount+=Number(cur.Amount)
}
else{
acc.push({...cur, Amount: Number(cur.Amount)})
}
return acc
}, [])
})

欢迎任何帮助或建议!

您可以尝试state或ref,这取决于是否要更新UI部分,如果要更新UI,则state else ref执行

const[sum,setSum]=使用状态(0(或

const sumRef=useRef(0(

然后在之后

const sum = output.reduce((acc, cur)=> {
const found = acc.find(val => val.Day === cur.Day)
if(found){
found.Amount+=Number(cur.Amount)
}
else{
acc.push({...cur, Amount: Number(cur.Amount)})
}
return acc
}, [])
})

您可以选择setSum(sum)sumRef.current = sum

希望它能有所帮助,放心吧

相关内容

  • 没有找到相关文章

最新更新