sen*_*tor 10 javascript serialization node.js deserialization reactjs
我想序列化一个React元素(给定props的React组件的一个实例)并在其他地方反序列化它.你为什么问?我希望能够通过stdout从一个进程发送类,并在另一个进程中呈现它.我还希望渲染的组件是交互式的,所以简单地使用ReactDOM.renderToString()就不够了......
我尝试过的:
eval()它进行反序列化JSON.stringify()和JSON.parse()分别MyReactComponent.toString() 收益:
"function MyReactClass() {
_classCallCheck(this, MyReactClass);
_get(Object.getPrototypeOf(MyReactClass.prototype), 'constructor', this).apply(this, arguments);
}"
Run Code Online (Sandbox Code Playgroud)
它不包含我的组件特有的任何方法(例如render()或constructor()).
在JS Bin中查看此示例代码:http://jsbin.com/febuzupicu/edit? js,console,output
sen*_*tor -1
回答我自己的问题:
// If I stringify this
JSON.stringify({
type: `React.createClass({
render: function() {
return <span>{this.props.name}</span>
}
})`,
props: {
name: 'Jorge'
}
})
// Then I am able to parse it and deserialize it into a React element
let {type, props} = payload
// In Node
React.createElement(vm.runInNewContext(type, {React}), props)
// Not in Node
React.createElement(eval(type), props)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5062 次 |
| 最近记录: |