【发布时间】:2021-03-10 23:04:55
【问题描述】:
在 gatsby 项目中,我的一个组件中有静态查询,它获取对象数组。然后我取窗口宽度并根据每个屏幕可以显示的块数量细分该数组...
这是查询:
const { data } = useStaticQuery(graphql`
query AutomobilesQuery {
data: allStrapiAutomobiles(sort: { fields: created_at, order: ASC }) {
nodes {
id
slug
title
years
description {
id
}
thumbnail {
localFile {
childImageSharp {
fluid(maxWidth: 1920, quality: 100) {
...GatsbyImageSharpFluid_noBase64
}
}
}
}
}
}
}
`)
尺寸:
const size = Math.min(4, Math.ceil(width / 454))
所以第一个选项是
const groups = chunkArray(data.nodes, size)
窗口调整大小事件后data.nodes变成空数组....
然后我就这样做了:
const [groups, setGroups] = useState(chunkArray(data.nodes, size))
useEffect(() => {
setGroups(chunkArray(groups.flat(1), size)
}, [size])
现在它在窗口调整大小事件后确实有效,但现在如果我在本地页面之间导航,data.nodes 再次变为空数组...
问题是什么会导致这种行为?
这个数组大约有 30 个项目,可能是因为数组的大小? 我确实使用页面查询进行了测试,但它具有相同的行为......
几乎没有什么可以猜测的...... description.id 在某些项目上为空...
// 更新 于是代码切换到页面查询
index.js
const index = ({ location, data }) => {
<Layout>
<SEO />
...
<Autos automobiles={data.automobiles}/>
...
</Layout>
)
}
export const query = graphql`
query allAutomobilesThumbsQuery {
automobiles: allStrapiAutomobiles(sort: { fields: created_at, order: ASC }) {
nodes {
id
slug
title
years
description {
id
}
thumbnail {
localFile {
childImageSharp {
fluid(maxWidth: 1920, quality: 100) {
...GatsbyImageSharpFluid_noBase64
}
}
}
}
}
}
}
`
export default index
组件代码
const Autos = ({automobiles}) => {
const { width } = useDisplayDetect()
const size = Math.min(4, Math.ceil(width / 454))
const [groups, setGroups] = useState(chunkArray(automobiles.nodes, size > 1 ? size * 2 : size))
useEffect(() => {
setGroups(chunkArray(groups.flat(1), size > 1 ? size * 2 : size))
}, [width])
return (
...
)
}
export default Autos
同样的行为,首先加载一切正常,然后加载数据,automobiles.nodes空数组 那是在页面刷新或页面加载之后:
那是在导航之后...
【问题讨论】:
标签: javascript reactjs graphql gatsby