问题
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