2017-05-24 57 views
0

我試圖使用promise來填充反應組件。我調試過了,在之後調用裏面的語句this.setState({items: items}),所以render函數中的items數組總是空的。我也嘗試使用componentDidMount()使用promise的setState

這將是正確的方法?

interface Props extends React.Props<ItemsListComponent> { 
    isAddButtonClicked : boolean; 
    newItem : string; 
    } 

    interface State { 
     items : Array<ItemEntity>; 
    } 

    export class ItemsListComponent extends React.Component<Props, State> { 

    constructor(props: Props) { 
     super(props); 
     this.state = {items: []}; 
    } 

    public componentWillMount() { 
     itemAPI.getAllItems().then((items) => { 
      this.setState({items: items}) 
     }); 
    } 

    render() { 
    return(
     <div className="container"> 
     <div className="row"> 
      <ul className="list-group"> 
      {this.state.items.map((item : ItemEntity) => 
       // Each child in an array or iterator should have a unique "key" prop. React doc. 
       <li className="list-group-item" key={item.id}>{item.task}</li> 
      )} 
      </ul> 
     </div> 
     </div> 
    ); 
    } 
    } 

回答

2

問題是當React呈現組件時數據還不可用。在實踐中,你的代碼應該警惕這一點,無論是在組件或以上:

render() { 
    if(!this.state.items) return null; // or loading indicator, data has not returned yet 
    return (<div className="container"> 
     ... 
    </div>); 
} 
0

我會把itemAPI.getAllItems()放在組件的構造函數中。一旦物品到達,無論何時,狀態將被更新並且這將觸發render()

0

創建方法 'asyncUpdate(數據){this.setState(數據)}' 在構造函數中 設置 'this.asyncUpdate = this.asyncUpdate.bind(本)'

和你通話的承諾後觸發「 this.asyncUpdate(promisedData)」

應該幫助

0

從文檔:componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.你應該能夠讓你的要求在componentDidMount()。這可以確保在狀態改變時重新顯示。如果它仍然是空的,那麼渲染中的地圖有可能返回一個空數組。確保你正確地格式化從你的API返回的項目。有可能的答案是{ items: [] }.