2017-11-29 11 views
0

こんにちは私は非同期でいくつかの問題があります。 API呼び出しが、私はトラブル私の状態からオブジェクトを通してどのようにループを把握し、私がしようとしている(行でそれらを表示しようとしたのですコンポーネントがメテオールAPI呼び出しの前にレンダリングされる

// 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; 

componentwillmountで行われる前に呼び出されるレンダリングているようですカートを作成する)

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

答えて

0

あなたはまだ余分なrenderを取得しますが、私はあなたが.map()機能上のエラーを取得と仮定?

あなただけの本にあなたのコンストラクタを変更した場合:

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

あなたはnullオブジェクト上の.map使用することはできませんので、あなたが、エラーを取得することはできませんが、あなたは空の配列にそれを使用することができます。