繁体   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