我正在学习如何使用同步setState,但它并不适用于我的项目。我想在从Axios获得listingInfo之后更新状态,但是它不能工作,但是res.data工作正常。
class ListingItem extends Component {
constructor(props) {
super(props);
this.state = {
listingInfo: {},
open: false,
};
this.getListingData(this.props.itemId);
}
setStateSynchronous(stateUpdate) {
return new Promise((resolve) => {
this.setState(stateUpdate, () => resolve());
});
}
getListingData = async (item_id) => {
try {
const res = await axios.get(`http://localhost:5000/api/items/${item_id}`);
console.log(res.data);//it's working
await this.setStateSynchronous({ listingInfo: res.data });
// this.setState({
// listingInfo: res.data,
// });
console.log(this.state.listingInfo);//no result
} catch (err) {
setAlert('Fail to obtain listings', 'error');
}
};我真的很感激你的帮助!
发布于 2020-07-16 05:05:15
感谢@PrathapReddy!在完成setState之前,我使用了条件呈现来防止数据呈现。我在呈现部分添加了这一行代码:
render() {
if (Object.keys(this.state.listingInfo).length === 0) {
return (
<div>
Loading
</div>
);
} else {
return //put what you want to initially render here
}
}另外,不需要修改setState,普通的setState就可以了。希望这是有用的!
https://stackoverflow.com/questions/62917166
复制相似问题