【问题标题】:how to fetch request with updated information without adding it in dependency array in react?如何在不将更新信息添加到依赖数组中的情况下获取具有更新信息的请求?
【发布时间】:2023-02-04 21:07:09
【问题描述】:

fetchedAuthor 是作者对象。 isFollow 是他的粉丝数。当有人点击 follow 时,isFollow 发生变化。当 isFollow 发生变化时,我想重新运行 useEffect。当作者更改时,fetchedAuthor 更改但我不希望此 useEffect 重新运行,因为这严格用于追随者处理而不是作者处理但同时当作者更改时我希望此 useEffect 知道作者已更改所以下次isFollow 更改 useEffect 不使用以前的 fetchedAuthor 而是使用 fetchedAuthor 的最新值。

 useEffect(() => {
    setCurrentAuthor(fetchedAuthor) ;
  },[fetchedAuthor]) ;

 useEffect(async () => {
    try {
      const response = await fetch(`URL/${currentAuthor}/${isFollow}`);
      const data = await response.json();
      console.log(data);
    } catch (error) {
      console.error(error);
    }},[isFollow]) ;

这会帮助我得到适当的回应吗?

【问题讨论】:

    标签: javascript reactjs react-hooks dependencies


    【解决方案1】:

    使用 ref 存储当前的fetchedAuthor。每当 fetchedAuthor 更改时更新 ref。调用 api 时使用 ref 的值:

    const authorRef = useRef(fetchedAuthor);
    
    useEffect(() => {
      authorRef.current = fetchedAuthor;
    }, [fetchedAuthor]);
    
    useEffect(async() => {
      try {
        const response = await fetch(`URL/${authorRef.current}/${isFollow}`);
        const data = await response.json();
        console.log(data);
      } catch (error) {
        console.error(error);
      }
    }, [isFollow]);
    

    【讨论】:

      猜你喜欢
      • 2015-07-04
      • 2010-10-19
      • 2023-01-25
      • 2021-12-13
      • 2021-09-13
      • 1970-01-01
      • 2013-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多