【问题标题】:Do react render props cause remounting of the child components?反应渲染道具会导致重新安装子组件吗?
【发布时间】:2018-11-16 16:46:36
【问题描述】:

我只是想知道人们是否知道使用“渲染道具”模式是否会导致子组件的过度安装/卸载。 例如,改编自 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.PureComponent 带来的优势。这是因为对于新的 props,浅 prop 比较总是会返回 false,并且在这种情况下,每次渲染都会为 render prop 生成一个新值。

但是,将“安装!”当用户移动鼠标时被一遍又一遍地调用?

谢谢!

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    我继续尝试用小提琴回答我自己的问题。看来,“安装!”不会一遍又一遍地调用:

    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')
    );
    

    【讨论】:

      【解决方案2】:

      componentDidMount 只会被调用一次,但是每次你的 state/props 改变时 componentDidUpdate 会和你的渲染函数一起被调用多次。

      【讨论】:

        猜你喜欢
        • 2020-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-03
        • 1970-01-01
        • 2021-01-22
        • 2021-01-19
        相关资源
        最近更新 更多