【发布时间】:2023-03-09 23:56:01
【问题描述】:
我正在尝试了解两者之间的区别:
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>;
};
那么为什么在使用不同的结构时调用会发生变化?
任何链接或解释将不胜感激。
谢谢。
【问题讨论】:
标签: use-effect reason reason-react