【问题标题】:re-rendering React Component重新渲染 React 组件
【发布时间】:2018-04-22 20:08:27
【问题描述】:

我有一个 react 类,我需要在其中使用 shouldComponentUpdate(),以防止组件与其父级之间的无限循环。

我只是检查nextProps 的深层克隆是否等于this.props,如果不等于,我只更新组件。

到目前为止,一切都很好。 (?)

class Child extends Component {
  onComponentUpdate = (e) => {
    this.props.update(e)
  }
  shouldComponentUpdate(nextProps, nextState) {
    return  JSON.stringify(nextProps) !== JSON.stringify(this.props)
  }
  render() {
    return (
      <div>
        // some code that might trigger onComponentUpdate()
      </div>
    );
  }
}

现在,在我的父组件中,发生了一些事情,让我想要重新渲染子组件,而无需更改特定的道具。我现在所做的是更改状态中的计数器并将其作为道具传递给孩子。我从来没有对计数器本身做任何事情,它只是向孩子表明道具实际发生了变化,以便孩子应该更新。

class Parent extends Component {
  constructor() {
    super()
    this.state = { counter: 0 }
  }
  otherChildChanged = () => {
    this.setState({ counter: this.state.counter + 1 })
  }
  render() {
    return (
      <div>
        <Child
          counter={this.state.counter}
          update={"some function"}
          other={"props"}
        >
        </Child>
        <OtherChild onChange={this.otherChildChanged}>
        </OtherChild>
        // some code that might trigger onComponentUpdate()
      </div>
    );
  }
}

有没有更好的方法来做到这一点?

【问题讨论】:

  • 不知道为什么要重新渲染一个孩子,如果它的道具甚至没有改变?
  • 我有一个可调整大小的 div(单击并拖动边框和 div 及其邻居调整大小)。

标签: javascript reactjs components


【解决方案1】:

您应该将可调整大小的 div 的大小作为道具传递给子组件。这样,当它发生变化时,JSON.stringify(nextProps) !== JSON.stringify(this.props) 将变为 true 并且会发生重新渲染。

如果一个组件必须以某种方式运行(例如重新渲染),这取决于它的 Parent 上发生的事情,它应该作为一个 prop 传递给它。

【讨论】:

  • 我可以这样做,但我的元素正在使用 css(样式化组件)调整大小。我没有用 javascript 改变实际大小。它只需要知道它需要更新,因此如果最终组件没有对该尺寸执行任何逻辑,那么发送尺寸道具也会让人觉得多余/误导。
猜你喜欢
  • 2021-06-19
  • 1970-01-01
  • 2016-01-11
  • 2020-05-01
  • 2018-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多