我有一个使用 Redux 的 React 应用程序 redux-thunk
。给定需要从 API 获取信息的某个组件,我会调用绑定(bind)操作创建者以在安装后发出该请求:
componentDidMount() {
this.props.fetchSomething();
}
为了让 UI 知道它是否处于加载状态,我使用 loading
来自应用程序状态的变量。我的 reducer 处理 LOADING
的三种操作类型, SUCCESS
,和FAILURE
。 loading
变量设置为 true
当 LOADING
发出 Action ;然后将其设置为 false
上SUCCESS
和FAILURE
.
因此 render
中有以下内容方法:
render() {
if (this.props.loading) {
return <Spinner />;
}
return (
<div>
This part uses the fetched data, available via this.props.something
</div>
);
}
因为最初this.props.something
是 null
,我还必须在渲染所需模板之前检查它是否存在,因此上面的 if 语句变为:
if (!this.props.something || this.props.loading) {
return <Spinner />;
}
到目前为止,这种方法对我来说效果很好,但也存在一些问题,其中之一是:
The first time I access the page,
this.props.something
is not yet set. But the second time I access the page, with the app already loaded, that data had already been fetched once, sothis.props.something
will have been defined. Because of that, there is brief moment in which the if statement condition is FALSE and the actual component template gets rendered.
(1) 你们会如何解决这个问题?
(2) 通过您的方法,您将如何处理必须发出多个请求(例如其中五个请求)的组件,使用与上面相同的方法,但使用不同的 loading
/something
每个变量?我可以重复上面相同的方法,但会遇到已定义但未加载的每个资源的短暂 if 语句失败的问题。
最佳答案
1) 您有两个选择。您可以在 componentWillUnmount
上调度一些 RESET
操作并重置您的存储,this.props.something
将再次为 null。第二个选项是显示数据(如果您已有数据),显示微调器,并在第二次获取成功时将其合并在一起。 (取决于目的和用户界面)
2)我从来没有需要过它,但是如何将它存储在 redux 中作为映射 {componentName: returned} 并检查是否所有组件都已加载?
编辑:当您将 loading
的初始值设置为 true 时,您不需要检查某些属性。
关于reactjs - 在使用 Redux 和 redux-thunk 的 React 应用程序中处理加载状态,在获取数据一次后返回到组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47188186/