簡體   English   中英

為什么當狀態改變時我的組件沒有重新渲染?

[英]why my component didn't re-render when the state change?


存儲在道具中的值 1 和 2 和 3 的值是 Math.floor(Math.random() * 100) 所以我想知道什么時候我 setState 和 numQuestions 的值, numCorrect 變化和渲染方法是因為我知道為什么這個渲染沒有使三個值 1,2,3 再次被復制並且它們的值隨着兩個按鈕的每次單擊而改變,所以稱為。

class App extends Component {
      constructor(props) {
      super(props)
      this.proposedAnswer = Math.floor(Math.random() * 3) + this.props.value1 + this.props.value2 + this.props.value3;
      this.state = {
        numQuestions : 0,
        numCorrect : 0,
      }
   }

   rightanswer= ()=> {
        if(this.proposedAnswer === this.props.value1 + this.props.value2 + this.props.value3){
          this.setState((oldstate)=> ({
            numCorrect : oldstate.numCorrect +=1 ,
            numQuestions : oldstate.numQuestions += 1 ,
          }))
        }else{
             this.setState((oldstate)=> ({
             numQuestions : oldstate.numQuestions += 1 ,
         }))
     }
  }

   falseanswer= ()=> {
         if(this.proposedAnswer !== this.props.value1 + this.props.value2 + this.props.value3){
           this.setState((oldstate)=> ({
               numCorrect : oldstate.numCorrect +=1 ,
               numQuestions : oldstate.numQuestions += 1 ,
           }))
         }else{
               this.setState((oldstate)=> ({
               numQuestions : oldstate.numQuestions += 1 ,
         }))
        }
      }

   render() {
      return (
          <div className="App">
            <div className="game">
              <h2>Mental Math</h2>
              <div className="equation">
                  <p className="text">{`${this.props.value1} + ${this.props.value2} + 
                   ${this.props.value3} = ${this.proposedAnswer}`}</p>
              </div>
              <button  onClick={() => this.rightanswer()}>True</button>
              <button onClick={() => this.falseanswer()}>False</button>
              <p className="text">
                 Your Score: {this.state.numCorrect}/{this.state.numQuestions}
              </p>
             </div>
          </div>
       );
      }
    }

  export default App;

當狀態改變時,你的組件會重新渲染。 但是,您的 props 不會更改,因為您沒有從父組件傳入新的 props,因此value1value2value3保持不變。

如果您希望您的value在狀態更改時發生更改,一種方法是將所有value移動到狀態,在組件掛載時初始化它們,並在組件更新時更新它們:

  constructor(props) {
    super(props);
    this.state = {
      numQuestions: 0,
      numCorrect: 0
    };
  }

  componentDidMount() {
    this.generateValues();
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.numQuestions !== prevState.numQuestions) {
      this.generateValues();
    }
  }

  generateValues = () => {
    const values = [...Array(3)].map(() => Math.floor(Math.random() * 100));
    const correctAnswer = values.reduce((a, b) => a + b, 0);
    const proposedAnswer = Math.floor(Math.random() * 3) + correctAnswer;
    this.setState({
      value1: values[0],
      value2: values[1],
      value3: values[2],
      correctAnswer: correctAnswer,
      proposedAnswer: proposedAnswer
    });
  };

箭頭函數沒有this綁定(更多信息在這里)。 您還使用this.falseanswerbuttononClick上調用它們。 因此該類找不到綁定,因此該函數不返回任何內容,因為它就像它不存在一樣。 此外,當我們將函數傳遞給事件處理程序並且函數沒有參數時,最佳做法是像這樣傳遞函數: onClick={myFunciton}

因此,在您的情況下,我會將這些箭頭函數轉換為方法,在constructor函數中綁定它們並在onClick事件中調用它們

constructor(props) {
      super(props)
      this.proposedAnswer = Math.floor(Math.random() * 3) + this.props.value1 + this.props.value2 + this.props.value3;
      this.state = {
        numQuestions : 0,
        numCorrect : 0,
      }
      this.falseAnswer = this.falseAnswer.bind(this);
   }

  falseAnswer () { ...}

  render () {
   return (
   <button onClick={this.falseAnswer}>False</button>
   );
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM