当没有更改时,纯组件会渲染吗?

时间:2020-06-05 12:43:30

标签: reactjs react-native react-redux react-router

我有一个像这样的纯组件?

        Client client = ClientBuilder.newClient();
        WebTarget target = client.target("http://localhost:8082/TesoWS/services").path("tesoWS-UPLOAD");

        Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_XML);
        Response response = invocationBuilder.post(Entity.entity(documentoTWS, MediaType.APPLICATION_XML)); 

现在当我在我的otherComponent中使用此pureComponents

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

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

如果我没有通过道具mainContainerStyle,那么它可以正常工作,只有在进行一些更改时才呈现。

但是,如果我在道具中传递mainContainerStyle,那么即使没有更改,它也会每次渲染。每次渲染都会降低性能。有什么方法可以解决它,或者为什么会发生。

1 个答案:

答案 0 :(得分:0)

确保不要传递给mainContainerStyle={{...other stuff...}}之类的文字对象,并保存其状态。

示例

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>