使用相同的键渲染时,React组件会卸下

时间:2019-03-24 00:39:16

标签: reactjs

根据此link,您可以避免使用相同的键来卸载组件。在此示例中,iam使用相同的密钥,但是每次都会卸载该组件。我在做什么错了?

class Component1 extends React.Component{

  componentDidMount(){console.log('componentDidMount');}
  componentWillUnmount(){console.log('componentWillUnmount');}


  render(){

      console.log('render component1');
      return <div></div>;
  }


}

class App extends Component {

  flag = true;

  action1 = ()=>{
      this.forceUpdate();
  }

  render() {
    console.log('render App');
      if(this.flag){
        this.flag = false;
          return (<div>
            <Component1 key="kaka"/>
            <button onClick = {this.action1}>Click me</button>
          </div>);
      }
      else{
        this.flag = true;
        return (<span>
            <Component1 key="kaka"/>
            <button onClick = {this.action1}>Click me</button>
          </span>);
      }

  }
}

1 个答案:

答案 0 :(得分:1)

您的key无关紧要,因为父母在您的render内部进行了更改(从div变为span,反之亦然)。

React's Reconciliation documentation

  

该算法不会尝试匹配不同组件类型的子树。如果您发现自己在两种具有非常相似输出的组件类型之间交替,则可能需要使其成为相同的类型。实际上,我们没有发现这是一个问题。

Medium帖子的作者似乎提出了其他建议。我不认为这是正确的。使用key建议在更改树时保持稳定性,但是如上所述,当组件类型更改时,React不会打扰协调子树。