如何在挂载页面时仅分派一次?

How dispatch only once when mounting a page?

亲爱的朋友们下午好。我现在对每个动作都执行了调度。我只需要在挂载页面时分派一次,在卸载页面时将其删除。告诉我该怎么做。

const myRef = createRef<any>();


const KeyboardAvoidingWrapper: React.FC<IKeyboardAvoidingProps> = (
  props: IKeyboardAvoidingProps,
) => {
  const dispatch = useDispatch();
  dispatch(setReference(myRef));
  if (isAndroid) {
    return (
      <ScrollView ref={myRef} style={styles.scroll} contentContainerStyle={styles.scrollContent}>
        <KeyboardAvoiding>{props.children}</KeyboardAvoiding>
      </ScrollView>
    );
  }

  return (
    <KeyboardAwareScrollView
      ref={myRef}
      style={styles.scroll}
      extraHeight={40}
      contentContainerStyle={styles.scrollContent}
    >
      {props.children}
    </KeyboardAwareScrollView>
  );
};

试试这个

// Similar to componentDidMount
useEffect(() => {
    const dispatch = useDispatch();
    dispatch(setReference(myRef));

    return () => dispatch(deleteReference(myRef)); // delete here on unmount
  }, []);
}