React渲染属性会导致子组件重新挂载吗?

4

我想知道使用“渲染属性”模式是否会导致子组件过多的挂载和卸载。例如,从React文档(https://reactjs.org/docs/render-props.html)中适配:

<Mouse>
{mouse => (
    <ShowMousePosition mouse={mouse}/>
  )}
</Mouse>


class ShowMousePosition extends React.Component {
  componentDidMount(){
    console.log('mounting!')
  }
  render () {
    const {mouse} = this.props
    return (
      <p>The mouse position is {mouse.x}, {mouse.y}</p>
    )
  }
}

我知道React文档中说:

如果你在render方法内创建函数,使用render prop可能会抵消使用React.PureComponent带来的优势。这是因为浅层比较将始终对新属性返回false,在这种情况下每次渲染都会为render prop生成一个新值。

但是,当用户移动鼠标时,“mounting!”会一遍又一遍地调用吗?

谢谢!

2个回答

4

我尝试使用fiddle回答了自己的问题。看起来"mounting!"不会一遍又一遍地被调用:

https://jsfiddle.net/69z2wepo/186690/

这是代码:
class Hello extends React.Component {
  render() {
    return <Mouse>
   {mouse => (
       <ShowMousePosition mouse={mouse}/>
     )}
   </Mouse>
  }
}

class Mouse extends React.Component {
  constructor(props) {
    super(props);
    this.handleMouseMove = this.handleMouseMove.bind(this);
    this.state = { x: 0, y: 0 };
  }

  handleMouseMove(event) {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  }

  render() {
    return (
      <div style={{ height: 800, width: 800 }} onMouseMove={this.handleMouseMove}>

        {/*
          Instead of providing a static representation of what <Mouse> renders,
          use the `render` prop to dynamically determine what to render.
        */}
        {this.props.children(this.state)}
      </div>
    );
  }
}




   class ShowMousePosition extends React.Component {
  componentDidMount(){
    console.log('mountin!')
  }
  render () {
    const {mouse} = this.props
    return (
      <p>The mouse position is {mouse.x}, {mouse.y}</p>
    )
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

0

componentDidMount只会被调用一次,但是componentDidUpdate会在每次状态/属性改变时与您的render函数一起被多次调用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接