My React component uses data from socket.io as it's state.
I am unsure how to just update the state when the data is updated without re-rendering the entire component.
Example code.
var socket = io();
var data = {
components: [{key: '',name: '',markup: ''}]
};
socket.on('data', function(_) {
data = _;
});
var Components = React.createClass({
displayName: "Components",
getInitialState: function getInitialState() {
return data;
},
handleChange: function handleChange() {
this.setState(data);
},
render: function render() {
/* render */
}
});
ReactDOM.render(
React.createElement(Components, {
data: data
}),
document.getElementById('main')
);
You can add socket event listener to componentDidMount
, like this
var socket = io();
var data = {
components: [{key: '',name: '',markup: ''}]
};
var Components = React.createClass({
displayName: "Components",
componentDidMount: function () {
socket.on('data', this.handleData);
},
componentWillUnmount: function () {
socket.removeListener('data', this.handleData);
},
handleData: function (data) {
this.setState(data);
},
getInitialState: function () {
return data;
},
handleChange: function handleChange() {
this.setState(data);
},
render: function render() {}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With