【问题标题】:How to make a Gatsby Storyblok blog index page如何制作 Gatsby Storyblok 博客索引页面
【发布时间】:2021-02-06 09:05:57
【问题描述】:

我正在尝试渲染一个博客页面以显示所有 Storyblok 博客条目:

这是我的 blog.js 页面

import React from "react"
import Layout from "../components/layout"
import Blogposts from "../components/BlogPosts"
import StoryblokService from '../utils/storyblok-service'

export default class extends React.Component {
  state = {
    stories: {
    }
  }
  async getInitialStories() {
    let { data: { stories } } = await StoryblokService.get('cdn/stories?starts_with=blog')
    return stories
  }
  async componentDidMount() {
    let stories = await this.getInitialStories()
    if(stories.content) this.setState({ stories })
    console.log(stories)
    setTimeout(() => StoryblokService.initEditor(this), 200)
  }
  render() {
    return (
      <Layout>
        <Blogposts stories={this.state.stories.content} />
      </Layout>
    )
  }
}

console.log(stories)

返回我的博文

Blogposts 组件如下所示

import React from 'react'
const BlogPosts = (stories) => (
    <ul>
      {stories.map((story) => (
          <li key={story._uid}>
            { story.title }
          </li>
        )
      )}
    </ul>
)
export default BlogPosts 

但是当我运行它时,我得到了这个错误。

TypeError: undefined is not a function ('...stories.map...' 附近) 博文 src/components/BlogPosts.js:5

2 | 
  3 | const BlogPosts = (stories) => (
  4 |
> 5 |     <ul>
  6 |       {stories.map((story) => (
  7 |           <li key={story._uid}>
  8 |             { story.title }

任何帮助将不胜感激!谢谢。

【问题讨论】:

    标签: javascript reactjs gatsby storyblok


    【解决方案1】:

    您将undefined 传递给Blogposts,因为一开始您的状态中不存在content,并且您仅在获取数据后才设置它。

    【讨论】:

    • 谢谢,我该如何解决这个问题?
    • 你在stories有什么?
    • [Log] 数组 (2) (commons.js, line 714496) 0 {name: "A New Normal", created_at: "2020-10-23T08:38:08.235Z", published_at: “2020-10-23T10:25:51.301Z”,备用:[],id:25025557,...} 1 {名称:“你好”,created_at:“2020-10-19T15:47:50.907Z”,published_at:“ 2020-10-23T08:20:26.736Z",备用:[],id:24427984,...}
    • 所以,似乎没有content 键。只需删除该条件if(stories.content),并将像这样state = { stories: [] } 的状态设置为数组,而不是对象
    • 是的,有道理,仍然无法使用:> TypeError: stories.map is not a function
    【解决方案2】:

    您在 &lt;Blogposts stories={this.state.stories.content} /&gt; 此处传递故事,但该值是通过异步获取的。所以模板试图在const BlogPosts = (stories) =&gt; ()中的值可用之前渲染

    &lt;Blogposts stories={this.state.stories.content} /&gt; 更改为{this.state.stories.content &amp;&amp; &lt;Blogposts stories={this.state.stories.content} /&gt;}

    【讨论】:

    • 谢谢!我刚试过这个,现在页面呈现,但没有在任何地方显示 blogposts 组件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    相关资源
    最近更新 更多