问题
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')
);
回答1:
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() {}
});
来源:https://stackoverflow.com/questions/33940826/update-react-state-via-socket-io