【发布时间】:2016-10-21 13:59:54
【问题描述】:
当我尝试从 componentwillmount 函数中的 api 调用更新反应组件的状态时,它没有按预期工作。该值未设置。
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 没有意义跨度>
-
即使 this.state= 数据不工作
-
@RakeshYadav 您不应手动将任何值设置为
this.state,因为当您调用setState()时它们将被覆盖。 -
@Barry127 你可以直接在componentWillMount中更新状态。看到这个:componentWillMount() 是我们处理配置、更新状态以及为第一次渲染做准备的机会。至此,props 和初始状态就定义好了。我们可以安全地查询 this.props 和 this.state,确定它们是当前值。来自:here
标签: reactjs react-native