如何在 Apollo/GraphQL 和 React 中使用状态和使用查询?

uni*_*ise 4 apollo reactjs graphql react-apollo

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

...

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)
}
Run Code Online (Sandbox Code Playgroud)

Hem*_*ath 10

你可以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`

    }
Run Code Online (Sandbox Code Playgroud)


Ati*_*ngh 5

您是否在提前返回后不小心调用了 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}`
}
Run Code Online (Sandbox Code Playgroud)