如何在React JS中实现对象数组分页(不使用Context API)
不用Context API实现问卷分页切换
问题分析
你当前用map遍历问卷数组导致所有问卷同时渲染在一页,要实现单页单问卷的切换效果,核心是用组件内部状态控制当前显示的问卷项,不需要依赖Context API。
假设现有代码示例
import React from 'react'; const surveys = [ { id: 1, title: "问卷1", questions: [...] }, { id: 2, title: "问卷2", questions: [...] }, { id: 3, title: "问卷3", questions: [...] } ]; function SurveyPage() { return ( <div> {surveys.map(survey => ( <div key={survey.id}> <h2>{survey.title}</h2> {/* 问卷问题渲染 */} </div> ))} </div> ); } export default SurveyPage;
实现方案
用useState维护当前问卷的索引,只渲染对应索引的问卷,配合切换按钮控制索引变化即可实现需求。
修改后的完整代码
import React, { useState } from 'react'; const surveys = [ { id: 1, title: "问卷1", questions: [{ text: "问题1-1" }, { text: "问题1-2" }] }, { id: 2, title: "问卷2", questions: [{ text: "问题2-1" }, { text: "问题2-2" }] }, { id: 3, title: "问卷3", questions: [{ text: "问题3-1" }, { text: "问题3-2" }] } ]; function SurveyPage() { // 初始化当前问卷索引为0(第一个问卷) const [currentSurveyIndex, setCurrentSurveyIndex] = useState(0); const currentSurvey = surveys[currentSurveyIndex]; // 切换到下一个问卷 const handleNext = () => { if (currentSurveyIndex < surveys.length - 1) { setCurrentSurveyIndex(prev => prev + 1); } }; // 切换到上一个问卷 const handlePrev = () => { if (currentSurveyIndex > 0) { setCurrentSurveyIndex(prev => prev - 1); } }; return ( <div className="survey-container"> {/* 仅渲染当前选中的问卷 */} <div key={currentSurvey.id}> <h2>{currentSurvey.title}</h2> <div className="questions"> {currentSurvey.questions.map((question, idx) => ( <div key={idx} className="question"> <p>{question.text}</p> {/* 替换为你的问题输入组件,如单选框、输入框等 */} </div> ))} </div> </div> {/* 分页导航按钮 */} <div className="navigation-buttons"> <button onClick={handlePrev} disabled={currentSurveyIndex === 0}> 上一页 </button> <button onClick={handleNext} disabled={currentSurveyIndex === surveys.length - 1}> {currentSurveyIndex === surveys.length - 1 ? "完成" : "下一页"} </button> </div> </div> ); } export default SurveyPage;
核心要点
- 内部状态控制:通过
currentSurveyIndex跟踪当前显示的问卷,所有状态都在组件内部维护,完全不需要Context API。 - 精准渲染:不再遍历整个问卷数组,直接取出当前索引对应的问卷进行渲染,确保单页只显示一个问卷。
- 边界处理:按钮添加
disabled属性,防止用户切换到不存在的问卷页面。 - 体验优化:最后一页按钮自动切换为“完成”文字,符合用户操作预期。
- 答案存储扩展:如果需要保存用户的问卷回答,可以在组件内添加
const [answers, setAnswers] = useState({})状态,通过问卷ID关联存储回答内容。
内容的提问来源于stack exchange,提问作者Afridi Rahman
相关产品推荐
相关产品推荐

