javascript React.js 生成新的随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28143193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:29:25  来源:igfitidea点击:

React.js generate new random number

javascriptrandomnumbersreactjs

提问by Boyswan

I'm trying to create a new random number which will be set as state after a method. It works perfectly on refresh, but I can't 'generate' a new number after the button click.

我正在尝试创建一个新的随机数,它将在方法之后设置为状态。它在刷新时完美运行,但在单击按钮后我无法“生成”新数字。

Here's my code at the moment:

这是我目前的代码:

var QuizContainer = React.createClass({

  randomNumber: function(){
    return Math.floor((Math.random() * Data.length) + 0);
  },

  getInitialState: function(){
    var rand = this.randomNumber();
    return {
      answerList: Data[rand].answer,
      answerQuestion: Data[rand].question,
      correctAnswer: Data[rand].correct,
      score: 0,
      timer: 30
    }
  }, 

  success: function(){
    this.setState({score: this.state.score + 1})
  },

  fail: function(){
    this.setState({score: 0})
    this.getInitialState();
  },

  handleClick: function(child){
    child.props.singleAnswer == this.state.correctAnswer ? this.success() : this.fail()
  },

  render: function(){
    return(
      <div>
        <Timer timer={this.state.timer} />
        <Score currentScore={this.state.score} />
        <QuestionContainer answerQuestion={this.state.answerQuestion} />
        <ButtonContainer onClick={this.handleClick} correctAnswer={this.state.correctAnswer} answerList={this.state.answerList} />
      </div>
    )
  }

})

module.exports = QuizContainer;

If anyone's able to help I'd be very grateful! Thanks!

如果有人能够提供帮助,我将不胜感激!谢谢!

采纳答案by Brigand

getInitialStatereturns an object. You're just calling this.getInitialState()and throwing away the object. To update the state you need to call this.setState

getInitialState返回一个对象。你只是调用this.getInitialState()并扔掉对象。要更新您需要调用的状态this.setState

  fail: function(){
    this.setState(this.getInitialState());
  },

There's no magic wrapper around getInitialState, the function just does what you tell it to do, and it's used by react when instancing your component.

getInitialState 没有神奇的包装器,该函数只执行您告诉它执行的操作,并且在实例化组件时由 react 使用。

I removed this.setState({score: 0})because it's provided by your getInitialState.

我删除了,this.setState({score: 0})因为它是由您的 getInitialState 提供的。



Also, ButtonContainer should be passing the answer up, not updating its props and passing itself to the onClick callback. If you're reading props other than your own, something is wrong.

此外,ButtonContainer 应该传递答案,而不是更新它的 props 并将自身传递给 onClick 回调。如果你阅读的不是你自己的道具,那就有问题了。

回答by Daniel

See this example: https://jsfiddle.net/danyaljj/1cban4oy/

看这个例子:https: //jsfiddle.net/danyaljj/1cban4oy/

var colors = ['silver', 'gray', 'red', 'maroon', 'yellow', 'olive', 'lime', 'green', 
              'aqua', 'teal', 'blue', 'navy', 'fuchsia', 'purple']; 

var category = {"cat": "1"}; 

class SampleApplication extends React.Component {
  constructor(props) {
    super(props);
    this.state = { BKColor: 'red', question: {}};
  }
  render() {
    var rand = Math.floor((Math.random() * 8)); 
    return (
        <table> 
            <tr>
                <th style={{ backgroundColor: colors[rand] }}>Month</th>
                <th>{colors[1]}</th> 
              </tr>
              <tr>
                <td>January {rand}</td>
                <td>0</td>
              </tr>
              <tr>
                <td>February</td>
                <td></td>
              </tr>
        </table> 
        ); 
  }
}

React.render(<SampleApplication />, document.body);

I generate a table with one cell colored randomly.

我生成一个表格,其中一个单元格随机着色。