In the process of writing simple code implementation of MVC pattern, the most difficult thing is to manipulate DOM. So this time we’re going to use React. If you have used React, you know that when you update a view with React, you must use setState to change the state. This process needs to be actively invoked. Vue updates the view directly by assigning values to variables under data. Vue is so simple because of data hijacking. Therefore, the purpose of React is to achieve a similar effect to Vue.
The idea is to use reverse inheritance in higher-order components to hijack the state of wrapped components. This is a small training project, not so much 😂. The reason why it’s so boring is because I wrote about taming JavaScript with Type to get some practice with TypeScript.
All code visiblegithub.
// Some code
// Mvvm.tsx
const hocExtends = (WrapperComponent: ComponentClass) = > (
class extends WrapperComponent {
constructor(props: any) {
super(props);
}
render() {
let self = this;
this.state = new Proxy({ ...this.state }, {
get: function (target, key, receiver) {
return Reflect.get(target, key, receiver);
},
set: function (target, key, value, receiver) :any {
self.setState({
[key]: value
})
return Reflect.set(target, key, value, receiver); }})return super.render()
}
}
)
......
filterSearchStuff(searchStuff: string): void {
const { stuffData } = this.state;
let stuffItem: IStuff = stuffData.find((item: IStuff) = > item.stuff === searchStuff)
this.state.stuffItem = stuffItem;
// this.setState({
// stuffItem
// })}...Copy the code