【发布时间】:2020-11-26 15:15:40
【问题描述】:
我正在尝试在我的 react 应用中实现一个 firebase 存储数据库。
单击挑战按钮后,它会将其保存到数据库中,然后应打印在仪表板上。现在它进入了一个无限循环,我真的不知道为什么。有人可以帮忙吗? 另外,如何在.then之外设置setChall和setco2,以便在组件的返回中使用?
仪表板的以下部分代码:
const [challs, setChall] = useState([]);
const [co2, setco2] = useState(0);
const handleChall = (e) => setChall(e);
let getMe = (e) => (getMe = e);
const handleCo2 = (e) => {
setco2(co2 + e);
};
database
.collection("Dashboard")
.get()
.then((querySnapshot) => {
querySnapshot.forEach(function (doc) {
const challenge = doc.data().chall;
const takenco2 = doc.data().Co2Consumption;
console.log(challenge);
getMe(challenge);
handleCo2(takenco2); //causes an infinite loop
});
handleChall(getMe);
console.log(challs);
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
这是一个 ChooseChellenge.js 类
function Challange() {
const [isPopped, setPop] = useState(false);
const plsWork = (e) =>{
setPop(!isPopped);
const theOne = challs[e];
console.log(theOne);
addToFire(theOne);
}
const [challs, setChalls] = useState([]);
useEffect(() => {
const fetchData = async () => {
var challs = [];
await database
.collection("Challenges")
.get()
.then((snapshot) => {
snapshot.docs.forEach((doc) => {
challs.push(doc.data().ChallengeName);
});
});
setChalls(challs);
};
fetchData();
}, []);
const addToFire = (addThatCh) => {
const buttonChall = addThatCh;
//take that from db if possible
const co2c = 20;
database
.collection("Dashboard")
.add({
chall: buttonChall,
Co2Consumption: co2c,
})
.then((newDocument) => {
//how to change the ID to not have an automatic id
console.log("New document created with ID: ", newDocument.id);
})
.catch((error) => {
console.error(error.message);
});
};
//user with collection of challanges!!! the ID needs to be the name of the challenge! co2 is inside
return (
<>
{isPopped && <Dialog2 />}
<div className="challanges">
<h1 className="newchallenge">Choose New Challange</h1>
<button className="challangeBtn" onClick={() => plsWork(0)} >
{challs[0]} (31days)
</button>
<button className="challangeBtn" onClick={() => plsWork(1)} >
{challs[1]} (14days)
</button>
<button className="challangeBtn" onClick={() => plsWork(2)} >
{challs[2]} (31days)
</button>
<button className="challangeBtn" onClick={() => plsWork(3)} >
{challs[3]} (31days)
</button>
<button className="challangeBtn" onClick={() => plsWork(4)} >
{challs[4]} (365days)
</button>
</div>
</>
);
}
export default Challange;
【问题讨论】:
标签: javascript reactjs firebase infinite-loop