2019-11-15

import React, { Component } from "react";
import { View, Text } from "react-native";



var globalID = 0;
//@ts-ignore
function observable(obj) {
  var oID = ++globalID;
  return new Proxy(obj, {
    get: function(target, key, receiver) {
      //@ts-ignore
      collect.startCollect(oID + "" + key);
      return Reflect.get(target, key, receiver);
    },
    //@ts-ignore
    set: function(target, key, value, receiver) {
      Reflect.set(target, key, value, receiver);
      //@ts-ignore
      collection[oID + "" + key] && collection[oID + "" + key].forEach(c => {
          c();
          if($render && $forceUpdate){
            $render()
            $forceUpdate()
          }
        });
    }
  });
}
var collection = {};
var collect = {
  //@ts-ignore
  begin: function(handler) {
    //@ts-ignore
    collection.handler = handler;
    //@ts-ignore
    collection.now = true;
  },
  //@ts-ignore
  startCollect: function(oIDKey) {
    //@ts-ignore
    if (collection.now) {
      //@ts-ignore
      if (collection[oIDKey]) {
        //@ts-ignore
        collection[oIDKey].push(collection.handler);
      } else {
        //@ts-ignore
        collection[oIDKey] = [collection.handler];
      }
    }
  },
  end: function() {
    //@ts-ignore
    collection.now = false;
  }
};
let $render: any
let $forceUpdate: any
//@ts-ignore
function observableRender(handler) {
  collect.begin(handler);
  handler();
  collect.end();
  //@ts-ignore
  return function(tag){
    tag.prototype.componentWillMount = function() {
      $render = this.render.bind(this);
      $forceUpdate = this.forceUpdate.bind(this);
    }
    return tag
  }
}

var obj = observable({
  a: 0,
});
setInterval(()=>{
  obj.a = Math.random()
},100)
@observableRender(() => {
  obj.a;
})
class App extends Component {
  scrollView: any;
  currIndex: number;
  timer: any;
  state = {
    hide: true
  };
  render() {
    return (
      
        数值变化渲染::{obj.a}
      
    );
  }
}
export default App;

你可能感兴趣的:(2019-11-15)