Jak re-render vlastní háček po počáteční vykreslení

0

Otázka

Mám vlastní háček jménem useIsUserSubscribed že zkontroluje konkrétní uživatel je přihlášen. To vrací true, pokud uživatel je přihlášen, a false, pokud uživatel není objednané...

import { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import { checkSubscription } from "../services";

// this hook checks if the current user is subscribed to a particular user(publisherId)
function useIsUserSubscribed(publisherId) {
  const [userIsSubscribed, setUserIsSubscribed] = useState(null);
  const currentUserId = useSelector((state) => state.auth.user?.id);

  useEffect(() => {
    if (!currentUserId || !publisherId) return;

    async function fetchCheckSubscriptionData() {
      try {
        const res = await checkSubscription(publisherId);
        setUserIsSubscribed(true);
      } catch (err) {
        setUserIsSubscribed(false);
      }
    }

    fetchCheckSubscriptionData();
  }, [publisherId, currentUserId]);

  return userIsSubscribed;
}

export default useIsUserSubscribed;

...Mám tlačítko pomocí tohoto háku, které činí text podmíněně na základě booleovské vrátil z useIsUserSubscribed...

import React, { useEffect, useState } from "react";
import { add, remove } from "../../services";
import useIsUserSubscribed from "../../hooks/useIsUserSubscribed";

const SubscribeUnsubscribeBtn = ({profilePageUserId}) => {

  const userIsSubscribed = useIsUserSubscribed(profilePageUserId);
  
  const onClick = async () => {
    if (userIsSubscribed) {
       // this is an API Call to the backend
      await removeSubscription(profilePageUserId);

    } else {
      // this is an API Call to the backend
      await addSubscription(profilePageUserId);
    }
    // HOW CAN I RERENDER THE HOOK HERE!!!!?
  }

  return (
    <button type="button" className="sub-edit-unsub-btn bsc-button" onClick={onClick}>
          {userIsSubscribed ? 'Subscribed' : 'Unsubscribed'}
    </button>
  );
} 

Po onClick Rád bych, aby se překreslil můj useIsUserSubscribed hák Tak, že můj text tlačítka přepíná. Může to být provedeno?

3

Nejlepší odpověď

2

nelze použít useEffect v háčku pro tento účel zkuste toto :

háček :

function useIsUserSubscribed() {
  const currentUserId = useSelector((state) => state.auth.user?.id);


  const checkUser = useCallback(async (publisherId, setUserIsSubscribed) => {
    if (!currentUserId || !publisherId) return;
      try {
        const res = await checkSubscription(publisherId);
        setUserIsSubscribed(true);
      } catch (err) {
        setUserIsSubscribed(false);
      }
    
  }, [currentUserId]);

  return {checkUser};
}

export default useIsUserSubscribed;

součásti :

const SubscribeUnsubscribeBtn = ({profilePageUserId}) => {
    const [userIsSubscribed,setUserIsSubscribed]=useState(false);
    const { checkUser } = useIsUserSubscribed();

     useEffect(()=>{
        checkUser(profilePageUserId,setUserIsSubscribed)
     },[checkUser,profilePageUserId]);
  
  const onClick = async () => {
    if (userIsSubscribed) {
       // this is an API Call to the backend
      await removeSubscription(profilePageUserId);

    } else {
      // this is an API Call to the backend
      await addSubscription(profilePageUserId);
    }
    // HOW CAN I RERENDER THE HOOK HERE!!!!?
    checkUser(profilePageUserId,setUserIsSubscribed)
  }

  return (
    <button type="button" className="sub-edit-unsub-btn bsc-button" onClick={onClick}>
          {userIsSubscribed ? 'Subscribed' : 'Unsubscribed'}
    </button>
  );
} 

můžete také přidat nějaké zatížení státu v háčku a vrátit je příliš, takže si můžete zkontrolovat, zda proces je již hotovo, nebo ne

2021-11-24 03:03:13

Mám v úmyslu znovu použít tuto logiku v jiných částech, pokud aplikace. Co je lepší způsob, jak dělat to opakovaně v případě, že háček není nejlepší přístup?
Simone Anthony

@SimoneAnthony nic špatného s háčky a můžete ji použít ale také jsem si všiml, používáte redux, takže můžete použít redux-thunk akce příliš
Mohammad
2

Přidat dependece na useIsUserSubscribed je useEffect.

háček :

function useIsUserSubscribed(publisherId) {
    const [userIsSubscribed, setUserIsSubscribed] = useState(null);
    const currentUserId = useSelector((state) => state.auth.user?.id);
    // add refresh dependece
    const refresh = useSelector((state) => state.auth.refresh);

    useEffect(() => {
        ...
    }, [publisherId, currentUserId, refresh]);
    ...
}

součásti :

const onClick = async () => {
    ...
    // HOW CAN I RERENDER THE HOOK HERE!!!!?
    // when click, you can dispatch a refresh flag.
    dispatch(refreshSubState([]))
}

Vystavit forceUpdate metheod.

háček :

function useIsUserSubscribed(publisherId) {
    const [update, setUpdate] = useState({});
    const forceUpdate = () => {
        setUpdate({});
    }  

    return {userIsSubscribed, forceUpdate};
}

součásti :

const {userIsSubscribed, forceUpdate} = useIsUserSubscribed(profilePageUserId);

const onClick = async () => {
    ...
    forceUpdate();
}
2021-11-24 02:56:11
0

Tady je další řešení, které uživatel @bitspook

SubscribeUnsubscribeBtn má závislost na useIsUserSubscribed, ale useIsUserSubscribed nespoléhej se na nic z SubscribeUnsubscribeBtn. Místo toho, useIsUserSubscribed je udržet místní státu. Máte několik možností zde:

  1. Tah státu, pokud jde whetehr uživatel je přihlášen nebo ne jeden, o úroveň výš, protože používáte Redux, možná v Redux.
  2. Komunikovat se useIsUserSubscribed že budete muset změnit svůj vnitřní stav.

Pro 1)

  const [userIsSubscribed, setUserIsSubscribed] = useState(null);

tah tohoto státu Redux store a používat jej s useSelector.

Pro 2), vrátí pole hodnota a zpětné volání z háku, místo toho jen hodnotu. To vám umožní komunikovat ze složky zpět do háku.

V useIsUserSubscribed,

  return [userIsSubscribed, setUserIsSubscribed];

Pak v onClick, můžete volat setUserIsSubscribed(false), měnící háček je vnitřní stav, a re-vykreslování komponenty.

2021-11-24 03:37:35

V jiných jazycích

Tato stránka je v jiných jazycích

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................