I\'m working on simple stream app. I have list of posts and this list can receive updates, which will display on top of it.
The problem is on each new post receive R
Work that needs to be done only once should be done in a lifecycle method that is guaranteed to run only once, like componentDidMount. As the docs suggest:
If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval, or send AJAX requests, perform those operations in this method.
I added logging to componentDidMount in your snippet to show rendering happens many times, but componentDidMount is called only once per instance.
class Post extends React.Component {
componentDidMount() {
console.log('mounted post', this.props.id);
}
render() {
console.log('rerendered post', this.props.id);
return (
- {this.props.post.text}
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.nextId = 4;
this.state = {
posts: [
{id: 1, text: 'First one'},
{id: 2,text: 'Second one'},
{id: 3,text: 'Third one'},
],
};
}
addPost() {
const posts = this.state.posts;
posts.unshift({id: this.nextId, text: 'Post ' + this.nextId});
this.nextId++;
this.setState({posts: posts});
}
render() {
return (
{this.state.posts.map((post, index) => {
return ( );
})}
);
}
}
ReactDOM.render( , document.getElementById('root'));