Created
January 8, 2016 23:47
-
-
Save anonymous/a826183547393c77a425 to your computer and use it in GitHub Desktop.
React triggers remounting when we use function as react component ( <Renderer /> ). When we don't and run Renderer() it's okay
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import * as ReactDOM from 'react-dom'; | |
var root = { | |
name: 'World', | |
children: [ | |
{name: 'Sun', id:1}, | |
{ | |
name: 'Earth', id:2, | |
children: [ | |
{name: 'Moon', id:3}, | |
{name: 'ISS', id:4}, | |
] | |
}, | |
] | |
}; | |
// function that returns stateless React component (i.e. just function) | |
// something like factory design pattern | |
function createRenderer(node, children) { | |
return () => (<li>{node.name}<ul>{children}</ul></li>); | |
} | |
// represents node in tree | |
class Node extends React.Component { | |
constructor(props) { | |
console.log('node constructor'); | |
super(props); | |
this.state = {node: props.node}; | |
} | |
componentDidMount() { | |
console.log('node did mount'); | |
} | |
componentWillUnmount() { | |
console.log('node will unmount') | |
} | |
render() { | |
console.log("node render"); | |
var node = this.state.node; | |
// calculate children markup | |
var children = (node.children || []).map( ch => <Node key={ch.id} node={ch} />); | |
var Renderer = createRenderer(node, children); | |
// ****** HERE: ****** | |
//return Renderer(); // uncommment and it's okay. | |
return <Renderer /> // when this executes there is unmounting-mounting | |
} | |
} | |
var instance = ReactDOM.render( | |
<Node node={root} />, | |
document.getElementById('container') | |
); | |
setTimeout( () => { | |
// state mutation | |
root.children[0].name = 'Black Hole'; | |
// update | |
instance.setState({node: root}); | |
}, 2000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment