I have a React component that's created dynamically, with data loaded into its state. This state is being cleared between click events, resulting in the visible
info being lost (undefined
). Where has it gone?
const React = require('react');
const ReactDOM = require('react-dom');
class App extends React.Component {
constructor(props) {
super(props);
this.nodesQuantity = 0;
this.state = {roots: []};
}
nextId(me) {
return me.nodesQuantity++;
}
componentDidMount() {
var roots = [1,2,3].map(node => {
let nextId = this.nextId(this);
return <Node key={nextId} data={node} nextId={this.nextId} depth={0} god={this} />
});
this.setState({roots: roots});
}
render() {
return (
<ul>{this.state.roots}</ul>
)
}
}
class Node extends React.Component{
constructor(props) {
super(props);
this.state = {data: this.props.data, childNodes: [], visible: true};
this.toggleExpanded = this.toggleExpanded.bind(this);
}
toggleExpanded(event) {
console.log(this.state.childNodes.length)
let val={id:"asdf",label:"asdf"}
if (this.state.childNodes.length > 0) {
this.state.childNodes.forEach((childNode) => {
childNode.setState({visible: !childNode.state.visible})
});
} else {
this.setState((oldState, props) => {
let nextId = props.nextId(props.god);
console.log(nextId);
oldState.childNodes.push(<Node key={nextId} data={val} nextId={props.nextId} depth={props.depth+1} god={props.god} />);
});
}
event.stopPropagation();
}
render() {
return (
<li onClick={this.toggleExpanded}>
{this.state.data.id} ({this.state.data.label})
<ul>{this.state.childNodes}</ul>
</li>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('react')
)