2.0.1 • Published 2 years ago
soul-react v2.0.1
react
类组件中
observer
注意:一旦使用了observer,请勿使用this.setState,observer监听的是constructor里的this.state,后续通过this.setState设置的this.state的变化,observer监听不到。
import React, {Component} from 'react';
import {observer} from "soul-function";
class App extends Component {
constructor(props) {
super(props);
this.state = {a:1}
this.data = observer(this)
}
handleAdd = ()=>{
this.data.a = this.data.a + 1
}
render() {
return (
<div>
<button onClick={this.handleAdd}>自增{this.state.a}</button>
</div>
);
}
}
export default App;
watcher
watcher函数能监听到this.state的属性变化,但是只能监听最外层的属性,暂时不支持深层的监听。watch的属性值必须是函数,可以是箭头函数,也可以是普通函数,函数的参数是当前属性的最新值
import React, {Component} from 'react';
import {watcher} from "soul-function";
class App extends Component {
constructor(props) {
super(props);
this.state = {a:1}
watcher(this)
}
watch = {
a:(value)=>{
console.log(value)
}
}
handleAdd = ()=>{
this.setState({
a:this.state.a + 1
})
}
render() {
return (
<div>
<button onClick={this.handleAdd}>自增{this.state.a}</button>
</div>
);
}
}
export default App;
函数组件中
observerOption
使用代理的模式,处理useState,当检测到值发生变化时,自动设置值,一个类似vue的data实现
import {useState} from "react";
import {observerOption} from "soul-function";
function App() {
const [init_state,setState] = useState({a:1})
const data = observerOption(init_state,setState)
const add = ()=>{
data.a = data.a + 2
}
return (
<div>
<button onClick={add}>add</button>
<div>
{ data.a }
</div>
</div>
);
}
lifeCycleOption
封装一个函数组件的生命周期,使函数组件更加规范
import {lifeCycleOption} from "soul-function";
import {useEffect} from "react";
const Test = ()=>{
const life_cycle = {
didMount:()=>{
console.log(123)
},
didUnMount:()=>{
console.log(789)
}
}
lifeCycleOption(life_cycle,useEffect)
return <div>
csa
</div>
}
export default Test