Node.js:如何对React组件进行序列化/反序列化? [英] Node.js: How to serialize/deserialize a React component?

查看:167
本文介绍了Node.js:如何对React组件进行序列化/反序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想序列化一个React元素(给定props的React组件的一个实例),然后在其他地方反序列化它.你为什么问?我希望能够从一个进程通过stdout发送该类,并在另一个进程中进行呈现.我还希望呈现的组件具有交互性,因此仅使用 ReactDOM.renderToString()就不能满足要求...

I would like to serialize a React element (an instance of React component given props) and deserialize it elsewhere. Why you ask? I would like to be able to send the class from one process over stdout and render it in another process. I also want the rendered component to be interactive, so simply using ReactDOM.renderToString() will not suffice...

我尝试过的事情:

  • 将其序列化为字符串并使用 eval()对其进行反序列化
  • 分别为 JSON.stringify() JSON.parse()使用自定义的替换器和reviver函数
  • Serializing it as a string and using eval() to deserialize it
  • Using a custom replacer and reviver functions for JSON.stringify() and JSON.parse() respectively

MyReactComponent.toString()返回:

"function MyReactClass() {
    _classCallCheck(this, MyReactClass);

    _get(Object.getPrototypeOf(MyReactClass.prototype), 'constructor', this).apply(this, arguments);
}"

其中不包含组件唯一的任何方法(例如 render() constructor()).

which doesn't contain any of the methods unique to my component (such as render() or constructor()).

请参见JS Bin中的以下示例代码: http://jsbin.com/febuzupicu/edit?js,console,输出

See this example code in JS Bin: http://jsbin.com/febuzupicu/edit?js,console,output

推荐答案

看看反应-序列化.这个包允许您将react组件序列化为JSON字符串然后返回.

Take a look at react-serialize. This package allows you to serialize react components into JSON strings and back.

这篇关于Node.js:如何对React组件进行序列化/反序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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