如果props更改,则ShouldComponentUpdate设置为false子组件不会更新

时间:2018-01-08 16:08:46

标签: reactjs lifecycle react-lifecycle

我的目标是渲染子组件而不重新渲染它的父组件。

因此,例如,App的状态作为prop直接传递给Column组件,但Column是Table的子项,Table的ShouldComponentUpdate设置为false(例如,表数据没有更改..) 。

问题..如果应用状态发生更改,则列组件不会更新..除非表组件上的ShouldComponentUpdate设置为true ..是否还有这个?

文档确实说

  

返回false不会阻止子组件重新呈现   当他们的状态发生变化时。

但是没有提及他们的道具是否会改变..

出于测试目的,我在这里创建了一个演示https://codesandbox.io/s/k2072rkp7o

预览代码:

const Column = ({ isSelected, onClick, children }) => (
  <div 
    style={{
      backgroundColor: isSelected ? 'green' : 'red',
      padding: '10px',
    }}
    onClick={onClick}
  >

    Column: {children}

  </div>
);

const Row = ({children }) => (
  <div 
    style={{
      backgroundColor: 'teal',
      padding: '10px'
    }}
  >

    Row {children}

  </div>
)


class Table extends React.Component {

  shouldComponentUpdate() {
    // There will be logic here to compare table data to see if its changed..
    return false
  }

  render() {

    return (
      <div 
        style={{
        backgroundColor: '#ccc',
        padding: '10px'
      }}>

      Table {this.props.children}

    </div>
    )
  }
}


class App extends React.Component {

  constructor() {
    super();
    this.state = {
      isSelected: false
    };
  }

  render() {

    return (
      <Table>

        <Row>
          <Column
            isSelected={this.state.isSelected}
            onClick={() => this.setState({
              isSelected: !this.state.isSelected
            })}
          />
        </Row>

      </Table>
    )
  }
}

3 个答案:

答案 0 :(得分:0)

考虑一个解决方案,您要设置默认状态onload并更新状态,其中与您的表进行交互,在您的列中附加“color-whateveryoulike”类。道具在这种情况下不会帮助你,因为我们从不想更新道具,你想要听取状态更新。

答案 1 :(得分:0)

你可以使用Table组件作为PureComponent,并且PureComponent internaly检查更改。

只需将class Table extends React.Component更改为class Table extends React.PureComponent,然后删除

shouldComponentUpdate() {
    // There will be logic here to compare table data to see if its changed..
    return false
  }

因为正如我所说的那样,PureComponent就是这样做的。 阅读更多信息:PureComponent 但是不要总是使用它,因为如果用于不必要的事情,它可能会减少你的应用程序的速度。

答案 2 :(得分:0)

好的,经过更多的阅读后,这是不可能的...当你玩桌子时想要将一种风格应用于单元组件而不会导致重新渲染整个表格时,这是不好的...必须研究替代方案......

对于遇到同样问题的人来说,组件生命周期是什么。

React Component lifecycle

相关问题