首页 > 解决方案 > 如何在 Apollo/GraphQL 和 React 中使用状态和 useQuery?

问题描述

我正在努力理解如何最好地组织我的代码以在 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)
}

标签: reactjsgraphqlapolloreact-apollo

解决方案


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

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`

    }

推荐阅读