我試圖使用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>
);
}
}