将 react 组件保存进数据库

#1

组件嘛,如果可以保存进数据库…

直接上代码~ 下方有 demo


// Utils
function convertComponentToString(component) {
  return String(component)
}

function convertStringToComponent(string_component) {
  return new Function('tmp', '', 'return ' + string_component)()
}

// Demo time

// 假设我们有一个 Timer 组件
class Timer extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      timer: 0
    }
  }

  componentDidMount() {
    this.timer = setInterval(() => {
        this.setState({timer: this.state.timer+1})
    }, 1000)
  }
  
  render() {
    return (
      <div onClick={this.simpleBehavior}>
        <div>Hello world {this.state.timer}</div>
      </div>
    )
  }
    
  simpleBehavior(){
    alert(233)
  }

  componentWillUnmount() {
    clearInterval(this.timer)
  }
  
}

// 将 Timer 转化为字符串(可以存进数据库)
const timer_str = convertComponentToString(Timer)

// 将转化的组件字符串再转为组件
const TimerComponent = convertStringToComponent(timer_str)

// 使用

ReactDOM.render(
  <TimerComponent />,
  document.getElementById('container')
);

Demo: jsbin

#2

可能会遇到的问题:

  1. 如果组件包含正则表达式,转化为字符串的时候,需要特殊处理;
  2. 需要先将 jsx 编译为 js 后再转为字符串;
  3. React 需要是全局的;
#4

可以存组件名和里面相应的数据。在前端在store里取相应的组件

#5

这种当然想过,对于组件很少没问题,但是随着组件越来越多,前端文件体积只会越来越大

#6

下载文件速度一般来说都要比你请求接口在下载来的快

#7

你说的场景和我的场景不一样,我的意思是:

组件写给用户用生成新的页面,比如有 100 个组件,用户可能只会用到 10 个组件。展示页面的时候,当然只加载其中 10 个就 ok 了。

#8

我想你可能需要的是
前端组件按需加载

#9

是。这组件给用户用的。

#10

有好的方案没?

#11

new Promise(function(resolve, reject) {

  setTimeout(() => resolve(1), 1000); // (*)

}).then(function(result) { // (**)

  alert(result); // 1
  return result * 2;

}).then(function(result) { // (***)

  alert(result); // 2
  return result * 2;

}).then(function(result) {

  alert(result); // 4
  return result * 2;

});