【问题标题】:How to re-render a custom hook [duplicate]如何重新渲染自定义挂钩 [重复]
【发布时间】:2022-01-02 12:18:57
【问题描述】:

我有一个名为useIsUserSubscribed 的自定义钩子,用于检查是否订阅了特定用户。如果用户已订阅则返回 true,如果用户未订阅则返回 false...

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;

...我有一个使用此挂钩的按钮,它根据从 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>
  );
} 

onClick 之后,我想重新渲染useIsUserSubscribed 挂钩,以便我的按钮文本切换。这可以做到吗?我应该使用不同的方法吗?

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    SubscribeUnsubscribeBtn 依赖于 useIsUserSubscribed,但 useIsUserSubscribed 不依赖于来自 SubscribeUnsubscribeBtn 的任何内容。 相反,useIsUserSubscribed 保持本地状态。你有几个选择:

    1. 将有关用户是否订阅的状态上移一级,因为您正在使用 Redux,可能在 Redux 中。
    2. 通知useIsUserSubscribed,您需要更改其内部状态。

    对于1)

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

    将此状态移动到 Redux 存储并与 useSelector 一起使用。

    对于2),返回一个值数组并从钩子中回调,而不仅仅是值。它将允许您从组件通信回钩子。

    useIsUserSubscribed

      return [userIsSubscribed, setUserIsSubscribed];
    

    然后在onClick,你可以调用setUserIsSubscribed(false),改变钩子的内部状态,重新渲染你的组件。

    【讨论】:

    • 因为这被标记为重复,你介意把你的答案放在这里吗? stackoverflow.com/questions/70090096/… 它会帮助很多人。我会确保给你一个赞成票。
    • 看起来你已经发布了另一个问题的答案。所以我想我会把它留在这里。
    猜你喜欢
    • 2021-12-06
    • 2020-07-20
    • 2022-01-02
    • 2021-11-02
    • 1970-01-01
    • 2022-01-17
    • 2021-04-13
    • 2021-11-11
    • 2020-06-27
    相关资源
    最近更新 更多