help to wacth state chagnes in react.js,just like the watcher
api in vue.js.
Requires React and Lodash.isequal.
npm install react-easy-watcher --save
-
Wrap a component to access
watcher
HOC. -
It is easy to watch
state
changes,you must have anObject
namedwatch
inthis.state
in your component,then you can watchstate
changes just like using watch invue
.the key of the object is the state you want to watch ,the value of the object is a function, When the field to be watched changes (support for deep listening), trigger this function. The parameters of the function are the values before and after the state changes
import React, { Component } from 'react';
import watcher from 'react-easy-watcher';
class Hello extends Component {
constructor(props) {
super(props)
this.state = {
msg: 'react-easy-watcher',
watch: {
msg(newVal,oldVal) {
console.log(newVal,oldVal,this)
}
}
}
}
change() {
this.setState({
msg: 'hello world!'
})
}
render() {
const { msg } = this.state
return (
<div>
<h1>{ msg }</h1>
<button onClick={this.change.bind(this)}>change</button>
</div>
)
}
}
export default watcher(Hello);
zysallen
MIT