我一直對(duì)php和sql比較感興趣,但是我決定更多地了解js。所以,我創(chuàng)建了測(cè)驗(yàn)應(yīng)用程序。(reactjs、nodejs 和 mongodb)應(yīng)用程序可以運(yùn)行!幾乎。有些事情我不滿(mǎn)意,我不知道如何解決。api.jsrouter.get('/', (req, res) => { Quiz.aggregate([ { $sample: { size: 1 } } ]) .then((data) => { console.log('Data: ', data); res.json(data); }) .catch((error) => { console.log('erorr: ', error) })});應(yīng)用程序.js getQuestionAndAnswers = () => { axios.get('http://localhost:8080/api') .then((response) => { const data = response.data; this.setState({posts: data}); console.log('Data has been received'); }) .catch(() => { alert('Error retrieving data'); }) } displayQuiz = (posts) => { if (!posts.length) return null return posts.map((post, index) => ( <div key={index}> <p>{post.question}</p> <button value={post.answer} onClick={(e) => this.checkAnswer(e, post)}><p>A. {post.answer}</p></button> <button value={post.answer2} onClick={(e) => this.checkAnswer(e, post)}><p>B. {post.answer2}</p></button> </div> )); }; checkAnswer = (e,post) => { console.log(e.currentTarget.value); if(e.currentTarget.value === post.c_answer){ console.log('correct'); }else{ console.log('incorrect'); } };正如您所看到的,我將數(shù)據(jù)存儲(chǔ)在按鈕值中,我認(rèn)為這不是最好的解決方案,因?yàn)榇鎯?chǔ)在那里的答案可能非常大,但我不知道如何做得更好。所以,我必須更改答案檢查,因?yàn)榇藭r(shí),我將正確答案與單擊的值進(jìn)行比較,是否有更好的解決方案?我想添加一個(gè)函數(shù),由于錯(cuò)誤的答案會(huì)將顏色更改為紅色,而正確的答案會(huì)將顏色更改為綠色,我想在執(zhí)行 if() 后添加 css 類(lèi)就足夠了。對(duì)于我點(diǎn)擊的按鈕來(lái)說(shuō),做到這一點(diǎn)并不困難,但是其余的呢?感謝您的任何建議!
存儲(chǔ)來(lái)自 mongodb 的值并驗(yàn)證
白板的微信
2023-09-07 10:11:29
