如何实时添加数据并在我的React应用中显示
导出默认函数 AllQuestion() { 让 [allQuestion, setAllQuestion] = useState([]); 让 isMounted = true; 让 [userAnswer, setUserAnswer] = useState(""); 常量导航 = useNavigate(); const getData = () =>; { const userId = sessionStorage.getItem("id"); Services.getAllQuestions(userId).then((res) => { 如果(已安装){ console.log(res.data); // - - - - - - - - - -参考 - - - - - - - - - - - setAllQuestion(res.data); } }); }; useEffect(() => { 获取数据(); 返回() => { 已安装=假; }; }, []); const submitAnswerHandler = (qid) =>; { 控制台.log(qid); 控制台.log(用户答案); const uid = sessionStorage.getItem("id"); const name = sessionStorage.getItem("name"); const dept = sessionStorage.getItem("部门"); const 角色 = sessionStorage.getItem("角色"); 常量日期=新日期(); 今天常量 = 日期.getDay() + “/”+ 日期.getMonth() + “/”+ 日期.getFullYear() + “在”+ 日期.getHours() + “:”+ 日期.getMinutes(); 常量answerObj = { 用户 ID:uid, 用户名:姓名, 用户部门:部门, 用户角色:角色, ansDate:今天, 答案:用户答案, Question_id: qid, }; // - - - - - - - - - 参考 - - - - - - - - - - - - - - Services.answerQuestion(uid, qid, answerObj).then((res) => { 成功(res.data); // - - - - - - - -参考 - - - - - - - - - - - - 导航('/home') console.log(res.data); }); }; 返回 ( <> <标题/>> <左容器>>
> {// - - - - - - - - - - -参考 - - - - - - - - - } <手风琴允许零展开> {allQuestion.map((问题) => (<页脚>> ); }<手风琴> <手风琴项目标题> {question.question} <手风琴类名称=“”> 提问者{question.userName};{question.userRole} - {question.userDepartment}于{question.quesDate}<小时/>>{question.answers.map((answer) => ( <手风琴项目面板 类名=“accordion__panel-cstm” 键={answer.id} >{answer.answer};回答者{answer.userName};{answer.userRole} - {answer.userDepartment}于 {answer.ansDate}<小时/>> ))}; <手风琴项目面板>回答这个问题 ;))}
在上面组件的渲染中,我得到了存储在服务器端的所有问题。然后我执行嵌套映射以遍历和显示数据。我还设置了答案并针对特定的 QuestionID 提交。我面临的问题是,当我发布答案时,我必须重新加载相同的组件才能获取更新的 allQuestion 对象数组,或者我必须导航到其他组件然后返回到此组件 ,即使导航到同一组件也不起作用。 我只想实时显示答案,而无需在将 answerObj 发送到服务器之前或之后再次加载组件。
allQuestion对象列表的结构
<前><代码>所有问题=[ { “问题ID”:qid, ...., ...., ...., 答案:[ { “answerId”:帮助, …… }, ] }]
export default function AllQuestion() { let [allQuestion, setAllQuestion] = useState([]); let isMounted = true; let [userAnswer, setUserAnswer] = useState(""); const navigate = useNavigate(); const getData = () => { const userId = sessionStorage.getItem("id"); Services.getAllQuestions(userId).then((res) => { if (isMounted) { console.log(res.data); //-------------------Reference---------------------- setAllQuestion(res.data); } }); }; useEffect(() => { getData(); return () => { isMounted = false; }; }, []); const submitAnswerHandler = (qid) => { console.log(qid); console.log(userAnswer); const uid = sessionStorage.getItem("id"); const name = sessionStorage.getItem("name"); const dept = sessionStorage.getItem("department"); const role = sessionStorage.getItem("role"); const date = new Date(); const today = date.getDay() + "/" + date.getMonth() + "/" + date.getFullYear() + " at " + date.getHours() + ":" + date.getMinutes(); const answerObj = { userId: uid, userName: name, userDepartment: dept, userRole: role, ansDate: today, answer: userAnswer, quesion_id: qid, }; //------------------Reference---------------------------- Services.answerQuestion(uid, qid, answerObj).then((res) => { toast.success(res.data); //---------------Reference------------------------ navigate('/home') console.log(res.data); }); }; return ( <> <Header /> <LeftContainer /> <ToastContainer/> <div className="right-question-div"> {//---------------------Reference------------------} <Accordion allowZeroExpanded> {allQuestion.map((question) => ( <AccordionItem key={question.id}> <Accordion> <AccordionItemHeading> <AccordionItemButton>{question.question}</AccordionItemButton> </AccordionItemHeading> <AccordionItemPanel className="accordion__panel-cstm "> <div className="detail-heading"> <u>Asked By</u> </div> <div className="detail">{question.userName}</div> <div className="detail"> {question.userRole} - {question.userDepartment} </div> <div className="detail">On {question.quesDate}</div> <hr /> <div> {question.answers.map((answer) => ( <AccordionItemPanel className="accordion__panel-cstm " key={answer.id} > <div > {answer.answer}</div> <div className="detail-heading"> <u>Answerd By</u> </div> <div className="detail">{answer.userName}</div> <div className="detail"> {answer.userRole} - {answer.userDepartment} </div> <div className="detail">On {answer.ansDate}</div> <hr /> <div></div> </AccordionItemPanel> ))} </div> </AccordionItemPanel> </Accordion> <Accordion className=""> <AccordionItemHeading className="a-inline-block"> <AccordionItemButton className="accordion__button-btn "> Answer This Question </AccordionItemButton> </AccordionItemHeading> <AccordionItemPanel> <div className="answering-div"> <form className="answer-form"> <div> {//----------------Reference-----------------} <textarea className="ans-box" onChange={(e) => setUserAnswer(e.target.value)} ></textarea> </div> <div> <button className="ans-btn" value={question.qid} onClick={(e) => { e.preventDefault(); submitAnswerHandler(question.id); }} > Answer </button> </div> </form> </div> </AccordionItemPanel> </Accordion> </AccordionItem> ))} </Accordion> </div> <Footer /> </> ); }
Here on render of the above component I get all the question stored on the server side . Then I perform nested mapping in order to traverse and display the data . Also I set answers and submit it for the particular questionID . The problem I am facing is that when I post an answer I have to either reload the same component in order to get updated allQuestion array of object or I have to navigate to some other component the come back to this component , even navigating to the same component don't work.
I just want to Display the answer on real-time without loading the component again before or after sending answerObj to the server.
The structure of allQuestion list of object
allQuestion=[ { "questionId":qid, ...., ...., ...., answers:[ { "answerId":aid, ..... }, ] }]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果要实现实时系统,则可以使用WebSocket协议。
在您的情况下,您只想在没有重新加载组件的情况下显示答案,只需将新问题对象推至
allquestion
导航。这样:对不起
,我的英语不好
If you want to implement a real-time system, you can using WebSocket protocol.
In your case, you just want to display the answer without reload the component, just push your new Question object to
allQuestion
intead of navigate.Like this:
Sorry for my bad English