reactjs - 如何在 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)
}
解决方案
你可以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`
}
推荐阅读
- php - Wordpress 忽略“post_status”更新
- ruby-on-rails-4 - Rails 4 中的 ActiveRecord 范围可以使用什么上下文?
- r - R - openxlsx 格式 - 有没有办法用 2 色渐变格式化单个单元格?
- python - 在屏幕上发布数据
- c# - 在 Update/FixedUpdate 以外的其他功能中旋转对象
- scala - 如何从 Json schem 文件创建 DataFrame Schema
- python - 如何在 Python 中使用随机索引处理多维列表
- sql-server - 3 个月平均值未显示正确结果
- reactjs - React,什么时候应该使用类组件,什么时候不使用类组件?
- typescript - Typescript - 类型“{}”缺少来自类型 {object} 的以下属性