混合使用三种状态进行转换会影响生命周期事件

时间:2018-12-15 18:20:44

标签: reactjs ocaml reason reason-react

我有一个带有三个渐变状态的ReasonReact叠加组件。第一个在完全不透明的情况下可见,第二个在几乎完全透明的状态下可见,第三个不显示。

是否可以使用生命周期事件来避免轮询以查看外部isOpen道具是否已切换?

我尝试从didReceiveProps和render调度更新(但是最终导致两种方法都出现无限循环或重大闪烁)。

我当前的组件。

type fading =
  | FadedIn
  | Intermediate
  | FadedOut;
type cycle =
  | In(fading)
  | Out(fading);

type action =
  | Cycle
  | PassTheCycle;

type state = {cycling};

let component = React.reducerComponent(__MODULE__);
let make =
    (~isOpen, ~onClick=None, children) => {
  ...component,
  didMount: ({send, onUnmount}) => {
    let interval = Js.Global.setInterval(() => PassTheCycle->send, 200);

    onUnmount(() => Js.Global.clearInterval(interval));
  },
  reducer: (action: action, state: state) => {
    let delay = (~delay=20, next) =>
      React.UpdateWithSideEffects(
        {cycling: next},
        ({send}) => Js.Global.setTimeout(() => Cycle->send, delay)->ignore,
      );

    switch (action) {
    | PassTheCycle =>
      switch (state.cycling) {
      | Out(FadedIn)
      | In(FadedOut) => React.SideEffects((({send}) => Cycle->send))
      | _ => React.NoUpdate
      }
    | Cycle =>
      switch (state.cycling) {
      | In(x) =>
        switch (x) {
        | FadedIn => React.NoUpdate
        | Intermediate => delay(~delay=200, In(FadedIn))
        | FadedOut => delay(In(Intermediate))
        }
      | Out(x) =>
        switch (x) {
        | FadedOut => React.NoUpdate
        | Intermediate => delay(~delay=200, Out(FadedOut))
        | FadedIn => delay(Out(Intermediate))
        }
      }
    };
  },
  initialState: () => {cycling: isOpen ? In(FadedIn) : Out(FadedOut)},
  willReceiveProps: ({state}) =>
    switch (isOpen, state.cycling) {
    | (false, In(x)) => {cycling: Out(x)}
    | (true, Out(x)) => {cycling: In(x)}
    | _ => state
    },
  render: ({state}) => {
    let className =
      Style.main(state.cycling);

    <div className> ...children </div>;
  },
};

0 个答案:

没有答案