首页 > 解决方案 > 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>

    )
}

标签: javascriptreactjs

解决方案


我正在考虑在 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…&lt;/div>        

    return (
      <div>
        <p>{this.state.questions[this.state.currentQuestion].content}</p>
        <button onClick={this.nextQuestion}>Next</button>
      </div>
    )
  }
}

推荐阅读