我正在尝试了解两者之间的区别:
React.useEffect(() => {
let timerId = Js.Global.setInterval(() => tick(),1000);
Some(() => Js.Global.clearInterval(timerId));
});
React.useEffect0(() => {
let timerId = Js.Global.setInterval(() => tick(),1000);
Some(() => Js.Global.clearInterval(timerId));
});
它们都具有相同的类型签名并且都可以编译,但是useEffect0
不执行任何操作:
// useEffect0 : unit => option(unit => unit) => unit
// useEffect : unit => option(unit => unit) => unit
要使用https://reasonml.github.io/reason-react/blog/2019/04/10/react-hooks上的示例,它使用useEffect
,但是如果您进行更改以使其使用useState
而不是useReducer
,则必须更改useEffect
到useEffect0
使用useEffect0
的原始版本:
type action =
| Tick;
type state = {
count: int,};
[@react.component]
let make = () => {
let (state,dispatch) = React.useReducer(
(state,action) =>
switch (action) {
| Tick => {count: state.count + 1}
},{count: 0}
);
React.useEffect0(() => {
let timerId = Js.Global.setInterval(() => dispatch(Tick),1000);
Some(() => Js.Global.clearInterval(timerId))
});
<div>{ReasonReact.string(string_of_int(state.count))}</div>;
};
在删除useReducer
并使用useEffect
之后:
[@react.component]
let make = () => {
let (state,dispatch) = React.useState(()=>
{count: 0}
);
let tick =()=> dispatch(_=>{count: state.count + 1});
React.useEffect(() => {
let timerId = Js.Global.setInterval(() => tick(),1000);
Some(() => Js.Global.clearInterval(timerId))
});
<div>{ReasonReact.string(string_of_int(state.count))}</div>;
};
那为什么在使用其他结构时呼叫会发生变化?
任何链接或解释将不胜感激。
谢谢。