-2

这是重现问题的 Codesandbox 链接: https ://codesandbox.io/s/boring-nash-svcj7?file=/src/index.js

我有一个奇怪的问题。我有一个非常简单的设置 Apollo 设置,仅用于测试目的。它是这样的:

function App() {
  return (
    <ApolloProvider client={client}>
      <Main />
    </ApolloProvider>
  );
}

它只是一个简单的 ApolloProvider,为 App 组件提供客户端。App 组件只有一行。

const Main = () => {
  const [data, setData] = useState();
  setData(1);
  return <div>Test</div>;
};

现在,当我刷新页面时,出现此错误:

Too many re-renders. React limits the number of renders to prevent an infinite loop.

有谁知道这里发生了什么?

为什么我不能在我的组件内部使用一个简单的钩子?

这是完整的代码:

import React, { useState } from "react";
import ReactDOM from "react-dom";

import ApolloClient from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { HttpLink } from "apollo-link-http";
import { ApolloProvider } from "@apollo/react-hooks";

const client = new ApolloClient({
  link: new HttpLink({
    uri: "https://api.graph.cool/simple/v1/swapi"
  }),
  cache: new InMemoryCache()
});

const Main = () => {
  const [data, setData] = useState();
  setData(1);
  return <div>Test</div>;
};

function App() {
  return (
    <ApolloProvider client={client}>
      <Main />
    </ApolloProvider>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

有一个我正在关注的例子,它确实有效,所以我不确定为什么我的例子不是。

https://codesandbox.io/s/replace-previous-results-with-next-results-nuu6x?file=/src/FilmTitles.jsx:16-24

4

2 回答 2

1

那么你不能setStaterender组件的功能。对于功能组件,它们的主体就是render功能。在这种情况下setData,更新触发重新渲染的状态,并在每次渲染setData时在无限循环中再次调用:

function App() {
    const [data, setData] = useState(0);
    setData(1); // this triggers re-render which is execution of App() which again calls setData(1)
}
于 2020-06-24T14:16:13.123 回答
0

像这样设置状态不是一个好主意,此时如果您只想尝试放入setDataauseEffect并且您不会再次收到此错误

  useEffect(() => {
    setData(1);
  }, [data]);
于 2020-06-24T14:35:15.087 回答