Pure Component renders when no change is there?

我只是一个虾纸丫 提交于 2020-06-16 18:34:32

问题


I have a pure Component like this?

interface Props {
 checkBoxTitleStyle?: any
  checkBoxBackgroundColor?: any
  onPressCheckBox?: (id, isChecked, selectedArray , options?: CheckBoxOptions) => void
  itemKey?: any
  mainContainerStyle?: any
}

class CheckBoxComponent extends PureComponent<Props> {
constructor()
render()
}

Now when i use this pureComponents in my otherComponent

   <CheckBoxComponent
          checkBoxKey={checkBoxKey}
          itemKey={get(item , 'id')}
          itemTitle={get(item , 'label', '')}
          isCheckBoxSelected={get(item , 'isChecked' , '')}
          checkBoxBackgroundColor={colors.DuckBlue}
        />

If i don't pass the prop mainContainerStyle then it works fine, it renders only when there is some change.

But if i pass mainContainerStyle in props then it renders everytime even if no change. Each render makes the performance slower . Is there is any way to fix it or why it is occuring so.


回答1:


Make sure you don't pass to prop literal object like mainContainerStyle={{...other stuff...}} and save state of it instead.

Example

const { PureComponent, useState, useEffect } = React;

class CheckBoxComponent extends PureComponent {
  constructor(props) {
    super(props);
  }
  
  render() {
    console.log('render');
    return <div>{JSON.stringify(this.props)}</div>
  }
}

const App = () => {
  const [mainContainerStyle, setStyle] = useState({position: 'absolute'});
  const [count, setCount] = useState(0);
  const checkBoxKey = 1;
  const item = {
    id: 1,
    label: 'label',
    isChecked: true,
    options: {}
  }
  const [options, setOptions] = useState(options);
  const [itemState, setItemState] = useState(item);
  const colors = {
    DuckBlue: ''
  }
  const get = (item, prop) => {
    return item[prop]
  }
  

return <div>
    <CheckBoxComponent
       checkBoxKey={checkBoxKey}
        itemKey={get(item , 'id')}
        itemTitle={get(item , 'label', '')}
        isCheckBoxSelected={get(item , 'isChecked' , '')}
        checkBoxBackgroundColor={colors.DuckBlue}
        //mainContainerStyle={{}} // causes re-render
        mainContainerStyle={mainContainerStyle} // state
        //options={get(item , 'options')} // causes re-render
        //options={itemState.options} // or
        options={options}
    />
    <button onClick={() => setCount(count => count + 1)}>Change Style</button>
  </div>
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>


来源:https://stackoverflow.com/questions/62215645/pure-component-renders-when-no-change-is-there

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!