通过 Socket.io 更新 React 状态 [英] Update React state via Socket.io

查看:42
本文介绍了通过 Socket.io 更新 React 状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 React 组件使用来自 socket.io 的数据作为它的状态.

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.

示例代码.

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')
);

推荐答案

你可以给componentDidMount添加socket事件监听器,像这样

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() {}
});

这篇关于通过 Socket.io 更新 React 状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆