【问题标题】:How to useState and useQuery in Apollo/GraphQL and React? [duplicate]如何在 Apollo/GraphQL 和 React 中使用状态和 useQuery? [复制]
【发布时间】:2020-06-29 08:22:01
【问题描述】:

我正在努力理解如何最好地组织我的代码以在 React 中设置初始 useState(),同时使用 GraphQL 和 Apollo 来引入数据。这是我的代码。如您所见,我想查看“数据”的一部分来设置初始状态,但是当我将 setSTate 移动到加载和错误行下方时,出现以下错误:

有条件地调用 React Hook “useState”。在每个组件渲染中,必须以完全相同的顺序调用 React Hooks。您是否在提前返回后不小心调用了 React Hook?反应钩子/钩子规则

我应该如何更好地组织这个?我是否必须使用 Apollo 的状态管理库,因为我更喜欢使用 React useState hooks。

const GET_LATEST_POSTS = gql`
query {
"graphql query is in here"
}

...

const Slider = () => {

const { data, loading, error } = useQuery(GET_LATEST_POSTS)

if (loading) return 'Loading...'
if (error) return `Error! ${error.message}`

const [ currentMovie, setMovie ] = useState(data)
}

【问题讨论】:

  • 如果您需要使用数据来初始化状态,请使用useEffect,正如答案中已经指出的那样。但是,仅当且仅当您打算稍后更改状态时,才应该像这样创建单独的组件状态。例如,如果您使用来自 Apollo 的数据来填充用户随后将编辑的表单。如果不是这种情况不是,那么您就不需要useState——直接使用data即可。

标签: reactjs graphql apollo react-apollo


【解决方案1】:

你可以像这样在 React 中使用useEffect

const Slider = () => {

    const { data, loading, error } = useQuery(GET_LATEST_POSTS)
    const [ currentMovie, setMovie ] = useState(undefined);

    useEffect(() => {
        if(loading === false && data){
            setMovie(data);
        }
    }, [loading, data])

    if (loading) return 'Loading...'
    if (error) return `Error! ${error.message}`
    // you can check if the currentMovie is undefined and use it to return something
    if(currentMovie) return `Movie ... do something with the currentMovie`

    }

【讨论】:

  • 对于打字稿,我还发现有必要在没有任何 if 语句的情况下返回 null。没有它,我的组件无法加载。 // 在等待数据时返回 null; .如果我没有它,我会收到此错误:渲染没有返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null。
【解决方案2】:

你是否在提前返回后不小心调用了 React Hook?

上面一行解释了你的错误。

根据钩子规则,你不应该在组件返回后调用 useState。

const Slider = () => {

const { data, loading, error } = useQuery(GET_LATEST_POSTS)


const [ currentMovie, setMovie ] = useState()

 useEffect(() => {
    if(!loading && data){
        setMovie(data);
    }
  }, [loading, data])

if (loading) return 'Loading...'               //your component's return should always be after all hook calls//
if (error) return `Error! ${error.message}`
}

【讨论】:

    猜你喜欢
    • 2017-09-01
    • 2020-12-20
    • 2017-01-15
    • 2019-09-14
    • 2020-11-08
    • 2020-12-14
    • 2021-03-02
    • 2019-09-17
    • 2020-10-30
    相关资源
    最近更新 更多