為了讓畫面reRender,每一個setter都要寫一次this.reRender()
請問有沒有好的寫法,讓我不用每寫一個setter或方法就要寫一次this.reRender() ?
或著有沒有其他較好的作法讓我在react裡面方便的使用class?
function Foo() {
const [render, setRender] = useState(false)
const reRender = () => {
setRender((state) => !state)
}
const [bar, setBar]
= useState(new ClassBar(reRender))
return (
<div>
</div>
)
}
class ClassBar {
reRender: () => void
constructor(reRender: () => void) {
this.reRender = reRender
}
_a = 1
get a() { return this._a }
set a(v: number) {
this._a = v;
this.reRender()
}
_b = 1
get b() { return this._b }
set b(v: number) {
this._b = v;
this.reRender()
}
_c = 1
get c() { return this._c }
set c(v: number) {
this._c = v;
this.reRender()
}
doSomething = () => {
this._a + 1
this._b + 1
this._c + 1
this.reRender()
}
}
可以直接把 class 裡面的值寫成 object
function Foo () {
const [values, setValues] = useState({ a: 1, b: 1, c: 1, d: 1 });
const updateValue = (value) => void setValues({
a: values.a + 1,
b: values.b + 1,
c: values.c + 1
});
retrun <></>;
}
或是利用 custom hook,就是自己寫一個 hook
// hook
function useMyHook () {
const [a, setA] = useState(1);
const [b, setB] = useState(1);
const [c, setC] = useState(1);
const [d, setD] = useState(1);
const dosomething = () => {
setA(a + 1);
setB(b + 1);
setC(c + 1);
setD(d + 1);
};
return { a, b, c, d, dosomething };
}
// Component
function Foo() {
const { a, b, c, d, dosomething } = useMyHook();
return <></>
}