reactjs - 如何在 Apollo/GraphQL 和 React 中使用状态和 useQuery?

标签 reactjs graphql apollo react-apollo

这个问题在这里已经有了答案:





Can you early return with React hooks?

(2 个回答)


2年前关闭。
社区在 7 个月前审查了是否重新打开此问题并将其关闭:

原始关闭原因未解决





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

React Hook "useState"被有条件地调用。在每个组件渲染中,必须以完全相同的顺序调用 React Hooks。你是否在提前返回后不小心调用了 React Hook? react 钩子(Hook)/钩子(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在 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`

    }

关于reactjs - 如何在 Apollo/GraphQL 和 React 中使用状态和 useQuery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60736179/

相关文章:

javascript - 在 Gatsby 中实现过滤器选项

reactjs - typescript React/Redux : Argument of type 'typeof MyClass' is not assignable to parameter of type 'ComponentType<...'

javascript - React - 用逗号解析用户输入的值并删除 CR/LF 和空格

swagger - JSON模式到GraphQL模式转换器

Python Graphene 处理多对多关系

javascript - 如何从 HTML 调用和形成 React.js 函数

GraphQL : Using Relay without having to use edges & node

javascript - graphql 突变如何接受 apollo 服务器表达的参数数组?

ApolloGraphQL : useSubscription Hook Syntax with onSubscriptionData?

javascript - 当使用 React Router v6 导航离开或关闭特定页面时,如何在 React 中发出请求?