我正在努力理解以下几个方面的区别:
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>;
};那么,为什么调用在使用不同的结构时会发生变化呢?
任何链接或解释将不胜感激。
谢谢。
发布于 2020-04-02 19:48:15
理性中的React.useEffect(f)编译为JavaScript中的React.useEffect(f)。理性中的React.useEffect0(f)编译为JavaScript中的React.useEffect(f, [])。
区别在于插入到[]中的第二个JavaScript参数。默认情况下,useEffect在JavaScript中会在每次呈现时触发。通过在第二个参数中添加空数组,我们告诉您只在组件第一次呈现时触发它一次。
https://stackoverflow.com/questions/60996617
复制相似问题