简体   繁体   中英

React how to keep rendered components

I am making a grid using divs in React. My Main component has a Settings component and a Boxes component.

在此处输入图片说明

Changing the value inside Settings will update a state value inside Main , which is passed to Boxes . Updating this value inside Settings will cause Boxes to rerender because it uses the state value of Main .

Since the amount of boxes doesn't change, I would like to only change the width and height of each individual box with JavaScript. Re rendering isn't necessary in this case.

I've tried to implement my width/height changing code in shouldComponentUpdate but this makes it so the boxes don't render at all and throws this error: Warning: Boxes.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.

So my question is: how can i keep these boxes rendered without having to re render, since updating the column count will only change width and height of each box?

Current implementation of shouldComponentUpdate:

shouldComponentUpdate() {

    let boxSize = this.state.wrapperWidth / this.props.columns;
    document.styleSheets[1].cssRules[0].style.setProperty('width', boxSize+"px", null);
    document.styleSheets[1].cssRules[0].style.setProperty('height', boxSize+"px", null);
}

Whenever a component receives props, it will render again. So when the state of your Main component is changed, it will trigger a render of Main which will inevitably pass props to Boxes and will trigger a render.

However you can use PureCompoonent to prevent rendering a component if the new props it received is the same as old props.

PureComponent does a shallow comparison of previous props and prevents re-render if the props are not changed.

import React, { PureComponent } from 'react';

class Boxes extends PureComponent {
  ... your commponent code
}

You can read more on PureComponent here - Official React Docs - PureComponent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM