我有以下代码:

const truth = [{
  question: "Question 1",
  hasAppeard: false
}, {
  question: "Question 1",
  hasAppeard: false
}]


当问题出现时,我试图将hasAppeard的值更改为true,这样我就可以过滤问题并仅显示onClick没有出现的问题。

我知道如何从类似这样的对象更改值:

const something = {
  a: false,
  b: false
}
something.b = true


但是在这种情况下,我陷入了困境,无法根据出现的问题找到如何访问和更改它的方法。

完整的代码如下:

Questions.js

const truth = [
  {question: "Question 1", hasAppeard: false},
  {question: "Question 2", hasAppeard: false},
  {question: "Question 3", hasAppeard: false},
  {question: "Question 4", hasAppeard: false}
]

const dare = [
  {question: "Question 5", hasAppeard: false},
  {question: "Question 6", hasAppeard: false},
  {question: "Question 7", hasAppeard: false},
  {question: "Question 8", hasAppeard: false}
]

export {truth, dare};


App.js

class App extends Component {
  constructor() {
  super();
  this.state = {
    currQuest: null,
  }
}

handleRandomTruth = () => {
  this.setState({
  currQuest: truth[Math.floor(Math.random() * truth.length)]
 })
}

handleRandomDare = () => {
  this.setState({
  currQuest: dare[Math.floor(Math.random() * dare.length)]
 })
}

render() {
 return (
  <div className="App">
     <div className="timer">
       <CountdownTimer />
     </div>

     <div className="current-player">
       <h3>current player</h3>
     </div>

     <div className="next-player">
       <h3>next player</h3>
     </div>

     <div className="questions">
        {this.state.currQuest ? <div>{this.state.currQuest.question}
      </div> : ''}
     </div>

   <button className="btn-truth" onClick=
     {this.handleRandomTruth}>Truth</button>
   <button className="btn-dare" onClick=
     {this.handleRandomDare}>Dare</button>
   <button className="btn-home" >Home</button>
  </div>
  );
 }
}

export default App;


我是编程新手,我想做一个真实的例子或敢于学习反应的游戏。我已经读过关于数组和对象的信息,但我很困惑,找不到我想要的东西。

先感谢您!

最佳答案

尝试这样的事情:

handleRandomTruth = () => {
  let validTruths = truth.filter(t => !t.hasAppeard);
  let randomNum = Math.floor(Math.random() * validTruths.length);
  this.setState({
    currQuest: validTruths[randomNum]
  })
  truth[randomNum].hasAppeard = true
}


相同的逻辑也吸引dare

10-07 11:58
查看更多