反应查询获取数据到 useState 导致错误

Dan*_*l L 0 reactjs react-query

我试图将获取的数据分配useQuery给一个状态,以根据请求是否为空来处理更好的条件渲染。

目前,我正在尝试做的事情如下所示:

...
const [userLists, setUserLists] = useState({});
...
const lists = useQuery(["lists"], api.fetchLists);

  if(lists.isLoading){
    //
  } else {
    setUserLists(lists.data.lists); // this line is causing the issue
  }
Run Code Online (Sandbox Code Playgroud)

浏览器返回给我一个Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

为什么会出现这种情况呢?如何将结果实际放入 useState 挂钩中?

小智 5

因此,这会导致无限循环,因为您正在组件内部设置状态。为了防止这种情况,请使用 useEffect 像这样:

const [userLists, setUserLists] = useState({});
...
const lists = useQuery(["lists"], api.fetchLists);

useEffect(() => {
    if (lists.isLoading) {
        // any loading state you might have
    } else {
        setUserLists(lists.data.lists); // this line is causing the issue
    }
}, [lists])
Run Code Online (Sandbox Code Playgroud)