【问题标题】:ReactJS & Firebase: How to fill the home page dynamically from Firebase DatabaseReactJS 和 Firebase:如何从 Firebase 数据库动态填充主页
【发布时间】:2021-01-04 07:09:06
【问题描述】:

我是 ReactJS 的超级新手。我在 Firebase 上部署了一个课程项目(我没有针对不同的分辨率进行动态缩放,现在在移动设备上效果更好):https://clean-kitchen.web.app/

目前,食谱按以下方式进行硬编码:

class Home extends Component {
  constructor(props) {
      super(props);
      this.state = {};
  }
  componentDidMount() {}
  componentWillUnmount() {}

  render() {
      return <>
          <GridCategory />
          <Paper elevation={0} square style={{ marginTop: "8px", marginBottom: "8px", padding: "8px"}}>
          <HeaderSuggestion title="Popular" icon="fire.png" />
          <GridSuggestion recipe="pasta alla carbonara" img="carbonara.jpg" />
          </Paper>
          <Paper elevation={0} square style={{ marginTop: "8px", marginBottom: "8px", padding: "8px"}}>
          <HeaderSuggestion title="Editor's Choice" icon="choice.png" />
          <GridSuggestion recipe="Cheesecake" img="cheesecake.jpg" />
          </Paper>
      </>
  }
}

我的目标是从实时数据库中获取当前食谱并动态创建页面。 Firebase 上的数据库设计如下:

我正在尝试通过以下方式获取数据库节点,但我无法使用 forEach 方法对此进行迭代。

var recipes = fire.database().ref("node_recipes/recipes");

如何正确迭代此变量并将配方名称和图像 URL 传递到“GridSuggestion”?谢谢!

【问题讨论】:

    标签: reactjs firebase firebase-realtime-database


    【解决方案1】:

    要迭代一个数组并为该数组的每个元素返回一个 JSX 元素,请使用 map。你的出租车做这样的事情:

    {recipes.map(recipe => (
        <GridSuggestion key={recipe.id} recipe={recipe.title} img={recipe.overviewImg} />
    ))}
    

    如果您想在循环中包含更多内容,例如您的 PaperHeaderSuggestion 组件,只需在地图的返回中添加 then 即可

    【讨论】:

    • 感谢您的回答!但是,我以这种方式遇到错误。它与我从数据库中获取数据的方式有关(因为它是 TypeError),但我不知道出了什么问题。 pasteboard.co/JI4gtkO.pngpasteboard.co/JI4gCW1.png
    • 错误字面意思就是问题所在。 recipes 不是数组。做一个fire.database().ref("node_recipes/recipes") 的控制台日志,看看你是否得到一个数组。如果没有,请尝试查找数组的位置。 map 是一个循环数组的函数。我假设recipes 已经是你所说和发布的数组
    • 正如您所说,错误与返回的数据类型有关,我已修复它。谢谢!
    • 没问题,很高兴我能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    相关资源
    最近更新 更多