渲染发生在componentwillmount Meteor API调用之前

时间:2017-11-29 00:51:51

标签: reactjs

您好我遇到了异步问题。似乎在componentwillmount

中完成api调用之前调用了render
// Framework
import React, { PureComponent } from "react";

// Components
import Page from "../components/Page.jsx";
import Button from "../components/Button.jsx";

class Home extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      order: null,
      error: null
    };
  }

  componentWillMount() {
    Meteor.call("orders.getLastOrder", (error, response) => {
      if (error) {
        this.setState(() => ({ error: error }));
        console.log(error);
      } else {
        this.setState(() => ({ order: response }));
        console.log(this.state.order[0].name);
      }
    });
  }

  goBack = () => this.props.history.push("/shop");
  goCart = () => this.props.history.push("/cart");

  render() {
    return (
      <Page pageTitle="Cart" history goBack={this.goBack} goCart={this.goCart}>
        <div className="home-page">
          <div>
          {this.state.order.map((item, i) => <div key={i}> {item.name}  
                      {item.price} {item.quantity}</div>)}
            </div>
          <Button
            onClick={() => {
              this.props.history.push("/shop");
            }}
          >
            Go shopping
          </Button>
        </div>
      </Page>
    );
  }
}

export default Home;

我无法弄清楚如何在我的状态中循环对象并将其显示在行中(我试图创建购物车)

0:{name: "TEMPOR Top", price: 875.5, quantitiy: 6}
1:{name: "CONSECTETUR Coat", price: 329.8, quantitiy: 3}
_id:"6RNZustHwbKjQDCYa"

1 个答案:

答案 0 :(得分:0)

您仍会获得额外的render,但我认为您在.map()函数上收到了错误消息?

如果您只将构造函数更改为:

constructor(props) {
    super(props);
    this.state = {
        order: [],
        error: null
    };
}

您不会得到错误,因为您无法在空对象上使用.map,但您可以在空数组上使用它。