代码之家  ›  专栏  ›  技术社区  ›  Michel

从React访问真实的数据库列表

  •  0
  • Michel  · 技术社区  · 4 年前

    我和 React Realtime Database .

    以下是与此问题相关的两个主要数据库节点:

    enter image description here

    以及:

    enter image description here

    以下是相关代码:

    class App extends React.Component {
      constructor(props) {
        super(props);
        firebase.initializeApp(config);
    
        this.state = {
          commandes: []
        };
      }
    
      componentDidMount() {
        this.getData();
      }
    
      getData = () => {
        let ref = firebase.database().ref("/");
        ref.on("value", snapshot => {
          const state = snapshot.val();
          this.setState(state);
        });
      };
    
      .....
    
      render() {
        const { commandes } = this.state;
        return (
          <React.Fragment>
            .....
                  {commandes.map(item => (
                    <div
                      key={item.name}
                      className="card float-left"
                      style={{ width: "18rem", marginRight: "1rem" }}
                    >
                    </div>
                  .....
                  ))}
            .....
          </React.Fragment>
        );
      }
    }
    

    它不起作用,这就是我得到的错误:

    TypeError: commandes.map is not a function
    

    这就是我发布这篇文章的原因。我很高兴能得到一些反馈或提示来解决这个问题。

    现在有一个重要的注意事项:当使用与上面相同的代码时,只需更改 命令 开发者 ,则代码可以完美地工作,列出集合中的项目 开发者 正如我所料。 虽然我花了一些时间尝试一些事情来解决这个问题,但它不起作用。 因为我没有改变代码(除了我刚才提到的),所以我假设不同的是不同的集合,但我真的看不出是什么。

    以下是在commandes集合中创建一项的函数:

      sendCommande = item => {
        const orderTime = new Date(),
        orderKey = orderTime.getTime().toString(),
        orderOject = {
          name: item.name,
          price: item.price,
          dateTime: orderTime.toLocaleString(),
          status: 1,
          uid: orderKey
        }
    
        firebase.database()
        .ref("/commandes/"+orderKey)
        .set(orderOject);
      };
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   Renaud Tarnec    4 年前

    我假设不同的是不同的系列(即 数据库节点),但我真的看不出是什么

    原因是 developers 节点子节点键按顺序排列: 0 , 1 , 2 这个 val() 方法将其解释为数组。

    系统的子节点键 commandes 节点没有遵循顺序:因此 val() 方法返回一个JavaScript对象(不是数组),因此错误为 map() .


    不是有些子节点键像 1. , 2. , 4 , 6 还将返回一个数组: val() 方法检测序列( 1. , 2. )并返回一个在索引处包含一些空元素的数组 0 , 3 5 .