我正在尝试理解以下两者之间的区别:
他们的类型签名相同,都可以编译通过,但是
要使用https://reasonml.github.io/reason-react/blog/2019/04/10/react-hooks中的示例,它使用
当使用不同的结构时,为什么调用会发生变化?
非常感谢任何链接或解释。
谢谢。
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>;
};
当使用不同的结构时,为什么调用会发生变化?
非常感谢任何链接或解释。
谢谢。
useEffect0
只会触发一次,并且只会执行一次useReducer
中的内容,这里是Tick
。在hook
的例子中,由于添加了空数组,useEffect
会触发一次tick()
。这样说清楚了吗? - armand