javascript - React - 一次显示一个数组值并通过单击更改
问题描述
我有一个包含 30 个问题的数组,我需要一次显示一个,让学生选择答案。
我正在考虑在 componentDidMount 中创建带有问题 0 的“currentQuestion”,当学生单击下一个时,我在计数器中添加 1 并将状态“currentQuestion”更改为下一个?
我想知道是否有更好的解决方案或者这是一个好主意?
编辑1:
我还没有开始构建,因为我不知道我的想法是否好,但在这种情况下,我正在显示 30 个问题,我想找到一种方法,一次显示一个,并在用户单击按钮时更改。
render () {
return (
<div>
{this.state.questions.map(item => (
<p key={item.id}>
{item.component[0].content}
</p>
))}
</div>
)
}
解决方案
我正在考虑在 componentDidMount 中创建带有问题 0 的“currentQuestion”
我猜您想存储currentQuestion
组件的状态?
如果是这样,您可以像这样在构造函数中初始化它:
class Quizz extends Component {
constructor() {
super();
this.state = {
currentQuestion: 0
}
}
}
对于组件的其余部分,我认为您的想法是正确的。
您最终会得到一个如下所示的组件:
class Quizz extends Component {
constructor() {
super();
this.state = {
questions: [],
currentQuestion: 0
}
this.nextQuestion = this.nextQuestion.bind(this)
}
componentDidMount() {
fetchQuestions().then(questions => this.setState({ questions }))
}
nextQuestion() {
this.setState(prevState => ({
currentQuestion: prevState.currentQuestion + 1
}))
}
render() {
if (!this.state.questions.length) return <div>Loading…</div>
return (
<div>
<p>{this.state.questions[this.state.currentQuestion].content}</p>
<button onClick={this.nextQuestion}>Next</button>
</div>
)
}
}
推荐阅读
- valueerror - ValueError:“攻击”不在列表中
- r - Bookdown 定义/描述列表?
- html - 如何判断 Chrome 表单不包含信用卡字段?
- php - Laravel 哎呀和类 str 未找到
- javascript - 从其他数组中的多个对象创建对象数组
- python - 用于简单重力模拟的 Python scipy.integrate.odeint 失败
- argparse - 传递字节参数时,Argparse 抛出错误(Python 3.7)
- javascript - WebSocket - 关闭窗口时可以运行自定义 onclose 函数吗?
- python - 全局变量声明+未绑定错误:分配之前引用的局部变量?
- javascript - 迭代嵌套对象并使用 es6+ 按值获取 obj