簡體   English   中英

父組件狀態改變,子組件不重新渲染

[英]State changed in parent component, child components do not re-render

我正在構建一個 whack-a-mole 應用程序,我有一個組件:

  • 渲染每一row
  • 生成一個隨機數,它是鼴鼠從哪個洞中彈出的index

這會每行生成 5 個孔,帶有隨機生成索引的孔會得到一個布爾值來標記它是否有痣。

mole被點擊時;

  • 它調用一個函數,通過分配一個新的隨機數來改變Row組件的狀態。
  • console.log()顯示它確實重新生成了一個隨機數,並且與每個Hole組件映射的變量也接收具有新索引的新的、更新的Hole組件以具有一個mole

挑戰
初始渲染效果很好。 痣被放置在隨機孔中,單擊時痣會消失。

然而,新索引中沒有出現molehole組件也沒有重新渲染,因為沒有任何組件console.log()出現。

即使父狀態發生了變化,並且重新渲染了一組holes的新道具,為什么 Hole 組件從未真正運行過?

更改孔數的方法在Row組件中,保存新組件的編號和變量也在那里。

所以我想問題可能出在 Hole 組件的某個地方。

class Rows extends Component{
    
    state = { holeNum: null  };

    componentWillMount() {
       this.changeSpot();
    };

    changeSpot = () => {
       // console.log(this.state.holeNum);
       let random = Math.floor(Math.random() * Math.floor(5));
       this.setState({ holeNum: random });
       // console.log("Spot changed ", this.state.holeNum, random)
    }

    render() {        
       // console.log("ROW ", this.props.id)
       let holes = [0,1,2,3,4];
       // console.log(this.state.holeNum)
       let row = holes.map(idx => {
          // if holeNum is equal to index has mole is true
          // console.log("rerendering")
          let moleRender = false;
          if(this.state.holeNum === idx){
              moleRender = true;
              // console.log(idx, moleRender, this.state.holeNum)            
          };
            
          return (
            <Hole
               changeSpot={this.changeSpot}
               updateScore={this.props.updateScore}
               hasMole={moleRender}
            />
          );
       });

       // console.log(row)

       return (
          <div className="Row">
             {row}
          </div>
       );
    };
};

這是Hole組件

class Hole extends Component{
    
    state = { hasMole: false };

    componentWillMount(){
       // console.log("Comp will mount Hole")
       if(this.props.hasMole===true){
          // console.log(this.props.hasMole)
          this.setState({hasMole:true});
       };
    };

    moleClickedHandler = () => {
       this.setState({ hasMole:false });
       // this.props.updateScore()
       this.props.changeSpot();
    };
    
    render() {
       let mole = null;
       if(this.state.hasMole === true){
           // console.log(this.state.hasMole)
           mole = <Mole clicked={this.moleClickedHandler} />;
       };

       return (
           <div className="Hole">
              {mole}
           </div>
       );
    };
};

謝謝!

我想您在開發人員工具的控制台中收到與缺少“密鑰”道具相關的警告您可以在此處了解更多為什么需要密鑰: https : //reactjs.org/docs/lists-and-keys.html

您可以通過添加密鑰來解決此問題

         <Hole
            key={ix}
            changeSpot={this.changeSpot}
            updateScore={this.props.updateScore}
            hasMole={moleRender}/>

暫無
暫無

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

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