如何让 React 组件等待 redux 存储变量被设置?
How to make React component wait for redux store variables to get set?
我正在开发一个 React 应用程序并使用 redux 来管理商店变量。存储变量在主页上的 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 调用,并使控制台混乱。
我想知道是否有办法让组件等待存储变量完成更新。
谢谢。
我会在子组件中放置一个加载微调器并默认显示它。然后我会在你的第二个 API 调用周围放置一个 if 语句,这样它只有在你需要的参数已经被初始化时才会被调用。像这样:
if (this.props.accountid && this.props.companyinfo && this.props.companyinfo.companyid) {
//do api call
}
然后用componentDidUpdate观察道具什么时候变化。当它们不再为 null 时,您可以调用 API 并将加载微调器替换为您等待 API 数据呈现的子组件的其余部分。
我正在开发一个 React 应用程序并使用 redux 来管理商店变量。存储变量在主页上的 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 调用,并使控制台混乱。
我想知道是否有办法让组件等待存储变量完成更新。
谢谢。
我会在子组件中放置一个加载微调器并默认显示它。然后我会在你的第二个 API 调用周围放置一个 if 语句,这样它只有在你需要的参数已经被初始化时才会被调用。像这样:
if (this.props.accountid && this.props.companyinfo && this.props.companyinfo.companyid) {
//do api call
}
然后用componentDidUpdate观察道具什么时候变化。当它们不再为 null 时,您可以调用 API 并将加载微调器替换为您等待 API 数据呈现的子组件的其余部分。