纯组件在没有变化时渲染?



我有这样的纯组件?

interface Props {
checkBoxTitleStyle?: any
checkBoxBackgroundColor?: any
onPressCheckBox?: (id, isChecked, selectedArray , options?: CheckBoxOptions) => void
itemKey?: any
mainContainerStyle?: any
}
class CheckBoxComponent extends PureComponent<Props> {
constructor()
render()
}

现在,当我在我的其他组件中使用此纯组件时

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

如果我不传递道具 mainContainerStyle,那么它工作正常,它仅在有一些变化时才呈现。

但是如果我在 props 中传递 mainContainerStyle,那么即使没有变化,它每次都会渲染。每次渲染都会使性能变慢。有没有办法解决它或为什么会这样。

> 确保不要像mainContainerStyle={{...other stuff...}}那样传递给 prop 文字对象并保存它的状态。

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>

最新更新