Update React state via Socket.io

自作多情 提交于 2021-02-18 06:58:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!