【问题标题】:FetchAPI Does Not Make Request After 2 CallsFetch API 在 2 次调用后未发出请求
【发布时间】:2022-01-24 18:42:39
【问题描述】:

我已经制作了一个 React 组件,它充当表格的弹出菜单(确切地说是 ag-grid),这意味着每次打开表格单元格时都会呈现该组件,然后每次单元格时都会卸载/删除已关闭。

我在其 useffect 中调用 FetchAPI 的组件,因此一旦从 GET 接收到组件所需的数据,它就会使用数据重新渲染组件

代码)

const myPopup = forwardRef((props, ref) => {
  const [componentData, setComponentData] = useState({});

  useEffect(() => {
    fetch(`myurl.com/getdata/1`)           //fetch from URL
        .then((response) => response.json())
        .then((data) => setComponentData(data));   //set component data hook with response (should trigger re-render with response data)
  }, []);

  console.log(componentData);
  . . .
});

当我第一次打开表格单元格时,组件显示完全符合预期,控制台显示两件事:

{}                      //from the initial state/render of component
{1:'res', 2:'imm',...}  //the data loaded (from the re-render after componentData is set to the FetchAPI result)

当我第二次打开表格单元格时,同样的事情:它按预期工作

当我第三次打开一个单元格时,我的组件以{}(初始状态)呈现,并且从 FetchAPI 中的数据永远不会发生重新呈现。看着控制台,我只有:

{}  //re-render never occured, meaning FetchAPI never called setComponentData() with it's response 

我对其进行了更深入的研究,似乎 FetchAPI 在这第三次根本没有进行调用,因为当我查看我们的服务器时,在前两个(这可以解释为什么组件永远不会重新渲染;FetchAPI 没有得到响应,因此永远不会到达 .then() 调用 setComponentData() )

既然如此,为什么 FetchAPI 在第二个之后没有进行调用?令我惊讶的是,这在前两次有效,但在之后无效。

任何帮助将不胜感激,这个错误已经让我发疯了几个星期了

【问题讨论】:

  • 有趣的问题。关于 ref 的一点在这里很突出。假设你有一些泄漏。有兴趣看看这是怎么回事。

标签: javascript reactjs api fetch fetch-api


【解决方案1】:

让我们从问题开始: 应该使用 ref 传递组件或传递对变量的引用,以免重新渲染访问该变量的组件。它们应该在 useEffect() 钩子中使用,而不是相反。如果要传递函数(例如 fetch 函数),请将其作为 prop 传递。然后,将该函数放入子组件的useEffect钩子中。

现在,回答您的问题: 组件渲染时调用 useEffect 挂钩。对组件的引用不会触发渲染。因此,它只会在初始渲染时触发 useEffect。

改为这样做:

const ParentComponent = () => {
 
 const myFetchFunction = async url => {
    fetch(url)           //fetch from URL
        .then((response) => response.json())

 return(
  ...
  <myPopup initFetchFunction={myFetchFunction}/>
...
);
//Or however you want to implement your component.
}

const myPopup = props => {
  const [componentData, setComponentData] = useState({});

  useEffect(() => {
   props.initFetchFunction(`myurl.com/getdata/1`).then((data) => setComponentData(data));
  }, []);

 useEffect(()=> {
   console.log(componentData);
 },[componentData];

  . . .
};

【讨论】:

  • 虽然我可能同意你所说的,但我认为这不是问题的根源。如果我在fetch 之前将console.log('useEffect Fired') 放在我的useEffect 中,它会显示在控制台中,这意味着我认为它应该进入useEffect 中的代码,但是那个获取只是没有解决
猜你喜欢
  • 2020-08-10
  • 2021-10-22
  • 2017-01-26
  • 2019-05-25
  • 2017-06-02
  • 2020-08-03
  • 1970-01-01
相关资源
最近更新 更多