Reactjs 如何使React组件等待redux存储变量设置?
我正在开发一个react应用程序,并使用redux管理商店变量。存储变量在主页上的API调用中得到更新,并在其他组件的API调用中用作查询参数 我在homepage组件中设置了store变量,如下所示:Reactjs 如何使React组件等待redux存储变量设置?,reactjs,redux,react-redux,aws-amplify,Reactjs,Redux,React Redux,Aws Amplify,我正在开发一个react应用程序,并使用redux管理商店变量。存储变量在主页上的API调用中得到更新,并在其他组件的API调用中用作查询参数 我在homepage组件中设置了store变量,如下所示: API.get("EmployerApiGw", "/employer/" + this.state.shadowAccountId).then(resp => { if (resp.items.length > 0) { this.setState({
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调用失败,因为此时存储变量为null
API.get("EmployerApiGw", "/employer/" + this.props.accountid + "/billingstatements", {
queryStringParameters: { companyid: this.props.companyinfo.companyid }
})
我的临时修复方法是使用componentdiddupdate()
调用componentDidMount()
,如果道具已更改(我将存储变量作为道具传递给组件)。这仍然会导致运行无效的api调用,但在存储变量更新后会重新呈现组件
componentDidUpdate(prevProps) {
if (JSON.stringify(prevProps) !== JSON.stringify(this.props)) {
this.componentDidMount();
}
}
这仍然会导致进行不必要的api调用,并使控制台变得混乱
我想知道是否有一种方法可以让组件等待存储变量完成更新
谢谢。我会在子组件中放置一个加载微调器,并在默认情况下显示该微调器。然后,我会在第二个API调用周围放一个if语句,这样只有在您需要的参数已经初始化的情况下才会调用它。大概是这样的:
if (this.props.accountid && this.props.companyinfo && this.props.companyinfo.companyid) {
//do api call
}
然后用它来观察道具的变化。当它们不再为null时,您可以调用API并用等待API数据呈现的子组件的其余部分替换加载微调器。是否调用子组件的componentDidMount()中的第二个API调用?如果订阅存储,则可以在值更改时调用API。这样,api在被调用时就不会被调用null@Paddy,是的,API调用位于componentDidMount()函数中。我按照你在回答中的建议做了。看起来效果不错。谢谢