【发布时间】:2019-08-27 16:49:30
【问题描述】:
我正在开发一个 react 应用程序并使用 redux 来管理商店变量。 store 变量在主页上的 API 调用中得到更新,并在其他组件的 api 调用中用作查询参数。
我在主页组件中设置了商店变量,如下所示:
API.get("EmployerApiGw", "/employer/" + this.state.shadowAccountId).then(resp => {
if (resp.items.length > 0) {
this.setState({
isValid: true,
openDialog: false
});
this.props.updateAccountid(this.state.shadowAccountId);
this.props.updateCompanyId(resp.items[0].companyid);
} else {
this.setState({
isValid: false
});
}
});
我遇到了一个问题,即在 api 调用中更新存储变量之前安装组件。这会导致其他 api 调用失败,因为此时存储变量为空。
API.get("EmployerApiGw", "/employer/" + this.props.accountid + "/billingstatements", {
queryStringParameters: { companyid: this.props.companyinfo.companyid }
})
我的临时修复是使用componentDidUpdate() 调用componentDidMount() 如果道具发生了变化(我将存储变量作为道具传递给组件)。这仍然会导致无效的 api 调用运行,但会在存储变量更新后重新渲染组件。
componentDidUpdate(prevProps) {
if (JSON.stringify(prevProps) !== JSON.stringify(this.props)) {
this.componentDidMount();
}
}
这仍然会导致不必要的 api 调用,并使控制台混乱。
我想知道是否有办法让组件等到存储变量完成更新。
谢谢。
【问题讨论】:
-
你是在调用子组件的componentDidMount()中的第二个API调用吗?
-
如果您订阅了商店,您可以在值更改时调用 api。这样,当它们为空时不会调用 api
-
@Paddy,是的,API 调用在 componentDidMount() 函数中。我做了你在回答中建议的事情。似乎工作得很好。谢谢!
标签: reactjs redux react-redux aws-amplify