Answer the question
In order to leave comments, you need to log in
How does render happen?
I can't figure out why my components keep getting render()
. I have a component Tree .
class Tree extends React.Component {
constructor(props) {
super(props);
this.state = {
oldValue: '',
newValue: '',
oldKey: '',
newKey: '',
level: '',
action: false,
};
this.onAddLevel = this.onAddLevel.bind(this);
}
resetState() {
this.setState({
action: false,
newKey: '',
newValue: '',
oldKey: '',
oldValue: ''
});
}
onAddLevel(e) {
e.preventDefault();
this.setState({
level: e.target.dataset.level,
oldKey: e.target.dataset.key,
action: 'add-level',
newValue: '',
newKey: ''
});
}
render() {
console.log('Tree');
return (
<div className="tree">
<TreeStructure
addLevel={this.onAddLevel}
structure={this.props.entity.structure}
/>
</div>
);
}
}
Tree.propTypes = {
entity: React.PropTypes.object.isRequired,
addLevel: React.PropTypes.func.isRequired
};
export default Tree;
import React from 'react';
import ControlLink from './ControlLink';
import isEmpty from 'lodash/isEmpty';
class TreeStructure extends React.Component {
constructor(props) {
super(props);
}
renderTree(object, level ='', padding = 0) {
console.log('render Tree');
padding += 12;
return (
Object.keys(object).map(key => {
if(typeof object[key] == 'string') {
return (
this.renderChildString(key, object[key], level ,padding)
)
} else {
return (
this.renderLevelString(key, object[key], level, padding)
);
}
})
);
}
renderChildString(key, value, level='',padding) {
return (
<div className="row-tree" style={{paddingLeft: `${padding}px`}} key={key} >
<b>{key}</b>: {value}
<div className="pull-right">
<ControlLink
title="Add level"
level={level}
keyVal={key}
className="create-element"
parentClassName="fa fa-plus"
onClick={this.props.addLevel}
/>
</div>
<div>
{this.renderTree(object, levelKey, padding)}
</div>
<div style={{paddingLeft: `${padding}px`}} className="row-tree">
<div>}</div>
</div>
</div>
);
}
render() {
console.log('render structure');
return (
<div>
{this.renderTree(this.props.structure)}
</div>
);
}
}
TreeStructure.propTypes = {
structure: React.PropTypes.object.isRequired,
addLevel: React.PropTypes.func.isRequired
};
export default TreeStructure;
Answer the question
In order to leave comments, you need to log in
Because starting Render on the parent starts Render on all child components. This is the essence of React.
You can manually control whether the component will be rendered if you add to it (in your case in the TreeStructure) the shouldComponentUpdate(nextProps, nextState)
function.
If it returns false, then the component will not be rendered.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question