首页 > 解决方案 > Firebase 实时数据库显示意外行为

问题描述

我正在为我的订单向 firebase 发出 POST 请求,但订单中的“成分”属性没有反映在 firebase 实时数据库中。除此之外,订单中的所有属性都会正确反映。请帮忙。

我的代码截图。

   orderHandler = (event) => {
    event.preventDefault();
    console.log('This is without JSON.stringify', this.props.ingredients);
    console.log(
      'This is with JSON.stringify',
      JSON.stringify(this.props.ingredients)
    );
    this.setState({ loading: true });
    const order = {
      price: this.props.price.toFixed(2),
      ingredients: this.props.ingredients,
      customer: {
        name: 'Tarun Singh',
        address: {
          street: 'TestStreet',
          zipCode: 42321,
          country: 'India',
        },
        email: 'test@test.com',
      },
      deleveryMethod: 'fastest',
    };
    console.log(
      'This is my order before making post request, ingredient property is present here',
      order
    );

    axios
      .post('/orders.json', order)
      .then((response) => {
        this.setState({ loading: false });
        this.props.history.push('/');
      })
      .catch((error) => {
        this.setState({ loading: false });
      });
  };

我的控制台输出也给出了我曾经使用过的 componentWillMount 警告,但之后我删除了它,但警告仍然存在。 在此处输入图像描述

但是,当我发出 POST 请求时,“ingredients”属性不会反映在 firebase 上。 在此处输入图像描述

标签: reactjsfirebasefirebase-realtime-database

解决方案


它看起来像这样的代码:

console.log(
  'This is with JSON.stringify',
  JSON.stringify(this.props.ingredients)
);

输出这个:

这是 JSON.stringify, []

所以看来,当这段代码运行时,你的this.props.ingredients还没有被填充。

当路径为空/没有值时,Firebase 不会存储它。这就解释了为什么ingredients您的应用程序的属性没有显示在数据库的 JSON 中。


推荐阅读