當我試圖更新來自componentwillmount函數中的api調用的反應組件的狀態它不按預期工作。該值沒有設置。狀態不更新componentWillMount
export default class ListOfProducts extends Component {
componentWillMount() {
console.log('component currently mounting');
fetchOrder().then(data => {
console.log('order api call has been finished.', data);
this.setState(data, function() {
//this should print new data but i am still getting old data
console.log('current this.state.', this.state.orders)
})
})
}
constructor(props) {
super(props);
this.state = {
"orders": {
"order_items": []
}
};
}
render() {
let productList = [];
let productUnit = (
<View>
{this.state.orders.order_items.map(function(order,i){
return <ProductListItem
delivered={true}
productSKU={3}/>
})}
</View>
);
return productUnit;
}
}
我不知道,但我認爲你可以直接修改狀態componentWillMount因爲組件沒有渲染它是沒有意義的調用setState或打電話給setState是componentDidMount – Barry127
即使this.state =數據不工作 –
@RakeshYadav你不應該手動設置任何值爲'this.state',因爲他們當你調用setState()時會被覆蓋。 –